task_type
stringclasses 4
values | code_task
stringclasses 15
values | start_line
int64 4
1.79k
| end_line
int64 4
1.8k
| before
stringlengths 79
76.1k
| between
stringlengths 17
806
| after
stringlengths 2
72.6k
| reason_categories_output
stringlengths 2
2.24k
| horizon_categories_output
stringlengths 83
3.99k
⌀ | reason_freq_analysis
stringclasses 150
values | horizon_freq_analysis
stringlengths 23
185
⌀ |
---|---|---|---|---|---|---|---|---|---|---|
completion_java | RNGTester | 392 | 394 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);'] | [' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));'] | [' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 392}, {'reason_category': 'Loop Body', 'usage_line': 393}, {'reason_category': 'Loop Body', 'usage_line': 394}] | Global_Variable 'gammas' used at line 392 is defined at line 382 and has a Short-Range dependency.
Class 'Gamma' used at line 392 is defined at line 276 and has a Long-Range dependency.
Function 'getPRNG' used at line 392 is defined at line 508 and has a Long-Range dependency.
Class 'GammaParam' used at line 392 is defined at line 246 and has a Long-Range dependency.
Variable 'd' used at line 392 is defined at line 391 and has a Short-Range dependency.
Global_Variable 'params' used at line 393 is defined at line 365 and has a Medium-Range dependency.
Global_Variable 'params' used at line 394 is defined at line 365 and has a Medium-Range dependency. | {'Loop Body': 3} | {'Global_Variable Short-Range': 1, 'Class Long-Range': 2, 'Function Long-Range': 1, 'Variable Short-Range': 1, 'Global_Variable Medium-Range': 2} |
completion_java | RNGTester | 414 | 416 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {'] | [' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }'] | [' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 414}, {'reason_category': 'Loop Body', 'usage_line': 415}, {'reason_category': 'Loop Body', 'usage_line': 416}] | Global_Variable 'gammas' used at line 414 is defined at line 382 and has a Long-Range dependency.
Variable 'v' used at line 415 is defined at line 409 and has a Short-Range dependency.
Variable 'i' used at line 415 is defined at line 411 and has a Short-Range dependency.
Variable 'g' used at line 415 is defined at line 414 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | RNGTester | 457 | 458 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {'] | [' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;'] | [' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'X' used at line 457 is defined at line 442 and has a Medium-Range dependency.
Global_Variable 'a' used at line 457 is defined at line 439 and has a Medium-Range dependency.
Global_Variable 'c' used at line 457 is defined at line 440 and has a Medium-Range dependency.
Global_Variable 'm' used at line 457 is defined at line 441 and has a Medium-Range dependency.
Global_Variable 'X' used at line 458 is defined at line 457 and has a Short-Range dependency.
Global_Variable 'max' used at line 458 is defined at line 443 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 5, 'Global_Variable Short-Range': 1} |
completion_java | RNGTester | 562 | 562 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {'] | [' return genUniform(params.getLow(), params.getHigh());'] | [' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Function 'genUniform' used at line 562 is defined at line 531 and has a Long-Range dependency.
Global_Variable 'params' used at line 562 is defined at line 546 and has a Medium-Range dependency. | {} | {'Function Long-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | RNGTester | 575 | 576 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {'] | [' low = lowIn;', ' high = highIn;'] | [' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'lowIn' used at line 575 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'low' used at line 575 is defined at line 572 and has a Short-Range dependency.
Variable 'highIn' used at line 576 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'high' used at line 576 is defined at line 572 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 2} |
completion_java | RNGTester | 602 | 604 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { '] | [' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);'] | [' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Class 'UniformParam' used at line 602 is defined at line 570 and has a Long-Range dependency.
Variable 'xmin' used at line 602 is defined at line 600 and has a Short-Range dependency.
Variable 'xmax' used at line 602 is defined at line 600 and has a Short-Range dependency.
Global_Variable 'xRegion' used at line 602 is defined at line 596 and has a Short-Range dependency.
Class 'UniformParam' used at line 603 is defined at line 570 and has a Long-Range dependency.
Variable 'ymin' used at line 603 is defined at line 601 and has a Short-Range dependency.
Variable 'ymax' used at line 603 is defined at line 601 and has a Short-Range dependency.
Global_Variable 'yRegion' used at line 603 is defined at line 597 and has a Short-Range dependency.
Variable 'xmax' used at line 604 is defined at line 600 and has a Short-Range dependency.
Variable 'xmin' used at line 604 is defined at line 600 and has a Short-Range dependency.
Variable 'ymax' used at line 604 is defined at line 601 and has a Short-Range dependency.
Variable 'ymin' used at line 604 is defined at line 601 and has a Short-Range dependency.
Global_Variable 'area' used at line 604 is defined at line 598 and has a Short-Range dependency. | {} | {'Class Long-Range': 2, 'Variable Short-Range': 8, 'Global_Variable Short-Range': 3} |
completion_java | RNGTester | 608 | 609 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {'] | [' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());'] | [' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Function 'genUniform' used at line 608 is defined at line 531 and has a Long-Range dependency.
Global_Variable 'xRegion' used at line 608 is defined at line 596 and has a Medium-Range dependency.
Function 'genUniform' used at line 609 is defined at line 531 and has a Long-Range dependency.
Global_Variable 'yRegion' used at line 609 is defined at line 597 and has a Medium-Range dependency. | {} | {'Function Long-Range': 2, 'Global_Variable Medium-Range': 2} |
completion_java | RNGTester | 652 | 652 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));'] | [' totalArea += (left*2.0 - left) * fx;'] | [' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 652}] | Variable 'left' used at line 652 is defined at line 649 and has a Short-Range dependency.
Variable 'fx' used at line 652 is defined at line 650 and has a Short-Range dependency.
Global_Variable 'totalArea' used at line 652 is defined at line 645 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1} |
completion_java | RNGTester | 663 | 665 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {'] | [' super(mySeed);', ' params = myParams;', ' setup ();'] | [' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'mySeed' used at line 663 is defined at line 662 and has a Short-Range dependency.
Variable 'myParams' used at line 664 is defined at line 662 and has a Short-Range dependency.
Global_Variable 'params' used at line 664 is defined at line 593 and has a Long-Range dependency.
Function 'setup' used at line 665 is defined at line 637 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 1, 'Function Medium-Range': 1} |
completion_java | RNGTester | 676 | 676 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {'] | [' area += s.getArea();'] | [' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 676}] | Variable 's' used at line 676 is defined at line 675 and has a Short-Range dependency.
Variable 'area' used at line 676 is defined at line 674 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 241 | 241 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {'] | [' if (j >= numRows || j < 0)'] | [' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 241}] | Variable 'j' used at line 241 is defined at line 240 and has a Short-Range dependency.
Global_Variable 'numRows' used at line 241 is defined at line 228 and has a Medium-Range dependency. | {'If Condition': 1} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | DoubleMatrixTester | 252 | 252 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {'] | [' if (i >= numCols || i < 0)'] | [' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 252}] | Variable 'i' used at line 252 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 252 is defined at line 227 and has a Medium-Range dependency. | {'If Condition': 1} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | DoubleMatrixTester | 260 | 260 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {'] | [' returnVal.setItem (row, myRow.getItem (i));'] | [' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 260}] | Variable 'returnVal' used at line 260 is defined at line 255 and has a Short-Range dependency.
Variable 'row' used at line 260 is defined at line 257 and has a Short-Range dependency.
Variable 'myRow' used at line 260 is defined at line 258 and has a Short-Range dependency.
Variable 'i' used at line 260 is defined at line 251 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Short-Range': 4} |
completion_java | DoubleMatrixTester | 267 | 267 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)'] | [' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 267}] | Variable 'j' used at line 267 is defined at line 266 and has a Short-Range dependency.
Global_Variable 'numRows' used at line 267 is defined at line 228 and has a Long-Range dependency.
Variable 'setToMe' used at line 267 is defined at line 266 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 267 is defined at line 227 and has a Long-Range dependency. | {'If Condition': 1} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 2} |
completion_java | DoubleMatrixTester | 258 | 261 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {'] | [' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }'] | [' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 258}, {'reason_category': 'If Condition', 'usage_line': 259}, {'reason_category': 'Loop Body', 'usage_line': 259}, {'reason_category': 'If Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 260}, {'reason_category': 'If Body', 'usage_line': 261}, {'reason_category': 'Loop Body', 'usage_line': 261}] | Global_Variable 'myData' used at line 258 is defined at line 226 and has a Long-Range dependency.
Variable 'row' used at line 258 is defined at line 257 and has a Short-Range dependency.
Variable 'myRow' used at line 259 is defined at line 258 and has a Short-Range dependency.
Variable 'returnVal' used at line 260 is defined at line 255 and has a Short-Range dependency.
Variable 'row' used at line 260 is defined at line 257 and has a Short-Range dependency.
Variable 'myRow' used at line 260 is defined at line 258 and has a Short-Range dependency.
Variable 'i' used at line 260 is defined at line 251 and has a Short-Range dependency. | {'Loop Body': 4, 'If Condition': 1, 'If Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 6} |
completion_java | DoubleMatrixTester | 273 | 274 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");'] | [' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 273}, {'reason_category': 'If Body', 'usage_line': 274}] | Variable 'i' used at line 273 is defined at line 272 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 273 is defined at line 227 and has a Long-Range dependency.
Variable 'setToMe' used at line 273 is defined at line 272 and has a Short-Range dependency.
Global_Variable 'numRows' used at line 273 is defined at line 228 and has a Long-Range dependency. | {'If Condition': 1, 'If Body': 1} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 2} |
completion_java | DoubleMatrixTester | 277 | 277 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {'] | [' IDoubleVector myRow = myData.get (row);'] | [' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 277}] | Global_Variable 'myData' used at line 277 is defined at line 226 and has a Long-Range dependency.
Variable 'row' used at line 277 is defined at line 276 and has a Short-Range dependency. | {'Loop Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 278 | 278 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);'] | [' if (myRow == null) {'] | [' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 278}, {'reason_category': 'If Condition', 'usage_line': 278}] | Variable 'myRow' used at line 278 is defined at line 277 and has a Short-Range dependency. | {'Loop Body': 1, 'If Condition': 1} | {'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 287 | 287 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {'] | [' if (j >= numRows || j < 0)'] | [' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 287}] | Variable 'j' used at line 287 is defined at line 286 and has a Short-Range dependency.
Global_Variable 'numRows' used at line 287 is defined at line 228 and has a Long-Range dependency. | {'If Condition': 1} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
completion_java | DoubleMatrixTester | 289 | 289 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");'] | [' if (i >= numCols || i < 0)'] | [' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 289}] | Variable 'i' used at line 289 is defined at line 286 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 289 is defined at line 227 and has a Long-Range dependency. | {'If Condition': 1} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
completion_java | DoubleMatrixTester | 302 | 303 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {'] | [' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);'] | [' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 302}, {'reason_category': 'Loop Body', 'usage_line': 303}] | Function 'getRow' used at line 302 is defined at line 64 and has a Long-Range dependency.
Variable 'i' used at line 302 is defined at line 300 and has a Short-Range dependency.
Variable 'curRow' used at line 303 is defined at line 302 and has a Short-Range dependency.
Variable 'sum' used at line 303 is defined at line 299 and has a Short-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 313 | 314 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {'] | [' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);'] | [' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 313}, {'reason_category': 'Loop Body', 'usage_line': 314}] | Function 'getColumn' used at line 313 is defined at line 71 and has a Long-Range dependency.
Variable 'i' used at line 313 is defined at line 311 and has a Short-Range dependency.
Variable 'curCol' used at line 314 is defined at line 313 and has a Short-Range dependency.
Variable 'sum' used at line 314 is defined at line 310 and has a Short-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 321 | 324 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {'] | [' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");'] | [' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 321}, {'reason_category': 'If Body', 'usage_line': 322}, {'reason_category': 'If Condition', 'usage_line': 323}, {'reason_category': 'If Body', 'usage_line': 324}] | Variable 'j' used at line 321 is defined at line 320 and has a Short-Range dependency.
Global_Variable 'numRows' used at line 321 is defined at line 228 and has a Long-Range dependency.
Variable 'i' used at line 323 is defined at line 320 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 323 is defined at line 227 and has a Long-Range dependency. | {'If Condition': 2, 'If Body': 2} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 2} |
completion_java | DoubleMatrixTester | 327 | 328 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {'] | [' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);'] | [' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 327}, {'reason_category': 'If Body', 'usage_line': 328}] | Global_Variable 'numCols' used at line 327 is defined at line 227 and has a Long-Range dependency.
Global_Variable 'backValue' used at line 327 is defined at line 229 and has a Long-Range dependency.
Variable 'myRow' used at line 327 is defined at line 325 and has a Short-Range dependency.
Global_Variable 'myData' used at line 328 is defined at line 226 and has a Long-Range dependency.
Variable 'j' used at line 328 is defined at line 320 and has a Short-Range dependency.
Variable 'myRow' used at line 328 is defined at line 327 and has a Short-Range dependency. | {'If Body': 2} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 358 | 358 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {'] | [' super (numCols, numRows, defaultVal); '] | [' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'numCols' used at line 358 is defined at line 357 and has a Short-Range dependency.
Variable 'numRows' used at line 358 is defined at line 357 and has a Short-Range dependency.
Variable 'defaultVal' used at line 358 is defined at line 357 and has a Short-Range dependency. | {} | {'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 362 | 362 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {'] | [' return getColumnABS (j); '] | [' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getColumnABS' used at line 362 is defined at line 251 and has a Long-Range dependency.
Variable 'j' used at line 362 is defined at line 361 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 366 | 366 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {'] | [' return getRowABS (i); '] | [' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getRowABS' used at line 366 is defined at line 240 and has a Long-Range dependency.
Variable 'i' used at line 366 is defined at line 365 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 370 | 370 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' setColumnABS (j, setToMe); '] | [' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setColumnABS' used at line 370 is defined at line 272 and has a Long-Range dependency.
Variable 'j' used at line 370 is defined at line 369 and has a Short-Range dependency.
Variable 'setToMe' used at line 370 is defined at line 369 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 376 | 379 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {'] | [' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);'] | [' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 376}, {'reason_category': 'Loop Body', 'usage_line': 377}, {'reason_category': 'Loop Body', 'usage_line': 378}, {'reason_category': 'Loop Body', 'usage_line': 379}] | Function 'getColumn' used at line 376 is defined at line 365 and has a Medium-Range dependency.
Variable 'i' used at line 376 is defined at line 375 and has a Short-Range dependency.
Variable 'toMe' used at line 377 is defined at line 373 and has a Short-Range dependency.
Variable 'i' used at line 377 is defined at line 375 and has a Short-Range dependency.
Variable 'curCol' used at line 378 is defined at line 376 and has a Short-Range dependency.
Variable 'hisCol' used at line 378 is defined at line 377 and has a Short-Range dependency.
Variable 'toMe' used at line 379 is defined at line 373 and has a Short-Range dependency.
Variable 'i' used at line 379 is defined at line 375 and has a Short-Range dependency.
Variable 'hisCol' used at line 379 is defined at line 377 and has a Short-Range dependency. | {'Loop Body': 4} | {'Function Medium-Range': 1, 'Variable Short-Range': 8} |
completion_java | DoubleMatrixTester | 384 | 384 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' setRowABS (i, setToMe); '] | [' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setRowABS' used at line 384 is defined at line 266 and has a Long-Range dependency.
Variable 'i' used at line 384 is defined at line 383 and has a Short-Range dependency.
Variable 'setToMe' used at line 384 is defined at line 383 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 388 | 388 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {'] | [' return getEntryABS (j, i); '] | [' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getEntryABS' used at line 388 is defined at line 286 and has a Long-Range dependency.
Variable 'j' used at line 388 is defined at line 387 and has a Short-Range dependency.
Variable 'i' used at line 388 is defined at line 387 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 392 | 392 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {'] | [' setEntryABS (j, i, setToMe);'] | [' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setEntryABS' used at line 392 is defined at line 320 and has a Long-Range dependency.
Variable 'j' used at line 392 is defined at line 391 and has a Short-Range dependency.
Variable 'i' used at line 392 is defined at line 391 and has a Short-Range dependency.
Variable 'setToMe' used at line 392 is defined at line 391 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 396 | 396 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {'] | [' return getNumColumnsABS (); '] | [' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getNumColumnsABS' used at line 396 is defined at line 337 and has a Long-Range dependency. | {} | {'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 400 | 400 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {'] | [' return getNumRowsABS ();'] | [' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getNumRowsABS' used at line 400 is defined at line 333 and has a Long-Range dependency. | {} | {'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 408 | 408 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {'] | [' super (numRows, numCols, defaultVal); '] | [' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'numRows' used at line 408 is defined at line 407 and has a Short-Range dependency.
Variable 'numCols' used at line 408 is defined at line 407 and has a Short-Range dependency.
Variable 'defaultVal' used at line 408 is defined at line 407 and has a Short-Range dependency. | {} | {'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 412 | 412 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {'] | [' return getRowABS (j); '] | [' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getRowABS' used at line 412 is defined at line 240 and has a Long-Range dependency.
Variable 'j' used at line 412 is defined at line 411 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 416 | 416 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {'] | [' return getColumnABS (i); '] | [' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getColumnABS' used at line 416 is defined at line 251 and has a Long-Range dependency.
Variable 'i' used at line 416 is defined at line 415 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 420 | 420 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' setRowABS (j, setToMe); '] | [' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setRowABS' used at line 420 is defined at line 266 and has a Long-Range dependency.
Variable 'j' used at line 420 is defined at line 419 and has a Short-Range dependency.
Variable 'setToMe' used at line 420 is defined at line 419 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 425 | 430 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();'] | [' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }'] | [' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 425}, {'reason_category': 'Loop Body', 'usage_line': 426}, {'reason_category': 'Loop Body', 'usage_line': 427}, {'reason_category': 'Loop Body', 'usage_line': 428}, {'reason_category': 'Loop Body', 'usage_line': 429}, {'reason_category': 'Loop Body', 'usage_line': 430}] | Variable 'i' used at line 425 is defined at line 425 and has a Short-Range dependency.
Variable 'numRows' used at line 425 is defined at line 424 and has a Short-Range dependency.
Function 'getRow' used at line 426 is defined at line 411 and has a Medium-Range dependency.
Variable 'i' used at line 426 is defined at line 425 and has a Short-Range dependency.
Variable 'toMe' used at line 427 is defined at line 423 and has a Short-Range dependency.
Variable 'i' used at line 427 is defined at line 425 and has a Short-Range dependency.
Variable 'curRow' used at line 428 is defined at line 426 and has a Short-Range dependency.
Variable 'hisRow' used at line 428 is defined at line 427 and has a Short-Range dependency.
Variable 'toMe' used at line 429 is defined at line 423 and has a Short-Range dependency.
Variable 'i' used at line 429 is defined at line 425 and has a Short-Range dependency.
Variable 'hisRow' used at line 429 is defined at line 427 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 5} | {'Variable Short-Range': 10, 'Function Medium-Range': 1} |
completion_java | DoubleMatrixTester | 434 | 434 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {'] | [' setColumnABS (i, setToMe); '] | [' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setColumnABS' used at line 434 is defined at line 272 and has a Long-Range dependency.
Variable 'i' used at line 434 is defined at line 433 and has a Short-Range dependency.
Variable 'setToMe' used at line 434 is defined at line 433 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 438 | 438 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {'] | [' return getEntryABS (i, j); '] | [' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getEntryABS' used at line 438 is defined at line 286 and has a Long-Range dependency.
Variable 'i' used at line 438 is defined at line 437 and has a Short-Range dependency.
Variable 'j' used at line 438 is defined at line 437 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 442 | 442 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {'] | [' setEntryABS (i, j, setToMe);'] | [' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'setEntryABS' used at line 442 is defined at line 320 and has a Long-Range dependency.
Variable 'i' used at line 442 is defined at line 441 and has a Short-Range dependency.
Variable 'j' used at line 442 is defined at line 441 and has a Short-Range dependency.
Variable 'setToMe' used at line 442 is defined at line 441 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 446 | 446 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {'] | [' return getNumRowsABS (); '] | [' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getNumRowsABS' used at line 446 is defined at line 333 and has a Long-Range dependency. | {} | {'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 450 | 450 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {'] | [' return getNumColumnsABS ();'] | [' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'getNumColumnsABS' used at line 450 is defined at line 337 and has a Long-Range dependency. | {} | {'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 488 | 488 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && '] | [' observed < goal + 0.000001)) {'] | [' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'observed' used at line 488 is defined at line 486 and has a Short-Range dependency.
Variable 'goal' used at line 488 is defined at line 486 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 503 | 505 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', ''] | [' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());'] | [' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 503}, {'reason_category': 'Loop Body', 'usage_line': 504}, {'reason_category': 'Loop Body', 'usage_line': 505}] | Class 'ColumnMajorDoubleMatrix' used at line 503 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 503 is defined at line 498 and has a Short-Range dependency.
Variable 'i' used at line 504 is defined at line 498 and has a Short-Range dependency.
Function 'ColumnMajorDoubleMatrix.getNumColumns' used at line 504 is defined at line 399 and has a Long-Range dependency.
Variable 'i' used at line 505 is defined at line 498 and has a Short-Range dependency.
Function 'ColumnMajorDoubleMatrix.getNumRows' used at line 505 is defined at line 395 and has a Long-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Short-Range': 3, 'Function Long-Range': 2} |
completion_java | DoubleMatrixTester | 527 | 527 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);'] | [' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);'] | [' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'ColumnMajorDoubleMatrix' used at line 527 is defined at line 355 and has a Long-Range dependency.
Variable 'numRows' used at line 527 is defined at line 521 and has a Short-Range dependency.
Variable 'numCols' used at line 527 is defined at line 521 and has a Short-Range dependency. | {} | {'Class Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 542 | 542 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);'] | [' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);'] | [' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'ColumnMajorDoubleMatrix' used at line 542 is defined at line 355 and has a Long-Range dependency. | {} | {'Class Long-Range': 1} |
completion_java | DoubleMatrixTester | 545 | 545 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);'] | [' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);'] | [' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'checkAllMatrixElementsEqualTo' used at line 545 is defined at line 555 and has a Short-Range dependency.
Variable 'cMatrix' used at line 545 is defined at line 542 and has a Short-Range dependency. | {} | {'Function Short-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 578 | 578 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {'] | [' checkCloseEnough(actual.getItem(i), expected[i]);'] | [' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 578}] | Function 'checkCloseEnough' used at line 578 is defined at line 486 and has a Long-Range dependency.
Variable 'actual' used at line 578 is defined at line 575 and has a Short-Range dependency.
Variable 'i' used at line 578 is defined at line 576 and has a Short-Range dependency.
Variable 'expected' used at line 578 is defined at line 575 and has a Short-Range dependency. | {'Loop Body': 1} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 590 | 590 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);'] | [' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);'] | ['', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'ColumnMajorDoubleMatrix' used at line 590 is defined at line 355 and has a Long-Range dependency. | {} | {'Class Long-Range': 1} |
completion_java | DoubleMatrixTester | 593 | 593 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);'] | [' trySimpleSetAndGetOnMatrix(cMatrix);'] | [' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'trySimpleSetAndGetOnMatrix' used at line 593 is defined at line 601 and has a Short-Range dependency.
Variable 'cMatrix' used at line 593 is defined at line 590 and has a Short-Range dependency. | {} | {'Function Short-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 719 | 720 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {'] | [' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {'] | [' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 719}, {'reason_category': 'Define Stop Criteria', 'usage_line': 720}, {'reason_category': 'Loop Body', 'usage_line': 720}] | Variable 'i' used at line 719 is defined at line 719 and has a Short-Range dependency.
Variable 'j' used at line 720 is defined at line 720 and has a Short-Range dependency. | {'Define Stop Criteria': 2, 'Loop Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 723 | 723 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column'] | [' matrix.setEntry(j, i, counter);'] | [' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 723}] | Variable 'matrix' used at line 723 is defined at line 718 and has a Short-Range dependency.
Variable 'j' used at line 723 is defined at line 720 and has a Short-Range dependency.
Variable 'i' used at line 723 is defined at line 719 and has a Short-Range dependency.
Variable 'counter' used at line 723 is defined at line 718 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 4} |
completion_java | DoubleMatrixTester | 725 | 725 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable'] | [' counter++;'] | [' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 725}] | Variable 'counter' used at line 725 is defined at line 718 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 719 | 725 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {'] | [' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;'] | [' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 719}, {'reason_category': 'Define Stop Criteria', 'usage_line': 720}, {'reason_category': 'Loop Body', 'usage_line': 720}, {'reason_category': 'Loop Body', 'usage_line': 721}, {'reason_category': 'Loop Body', 'usage_line': 722}, {'reason_category': 'Loop Body', 'usage_line': 723}, {'reason_category': 'Loop Body', 'usage_line': 724}, {'reason_category': 'Loop Body', 'usage_line': 725}] | Variable 'i' used at line 719 is defined at line 719 and has a Short-Range dependency.
Variable 'j' used at line 720 is defined at line 720 and has a Short-Range dependency.
Variable 'matrix' used at line 723 is defined at line 718 and has a Short-Range dependency.
Variable 'j' used at line 723 is defined at line 720 and has a Short-Range dependency.
Variable 'i' used at line 723 is defined at line 719 and has a Short-Range dependency.
Variable 'counter' used at line 723 is defined at line 718 and has a Short-Range dependency.
Variable 'counter' used at line 725 is defined at line 718 and has a Short-Range dependency. | {'Define Stop Criteria': 2, 'Loop Body': 6} | {'Variable Short-Range': 7} |
completion_java | DoubleMatrixTester | 761 | 761 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;'] | [' int numRows = actualMatrix[0].length;'] | [' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'actualMatrix' used at line 761 is defined at line 758 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 764 | 765 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix'] | [' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {'] | ['', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 764}, {'reason_category': 'Define Stop Criteria', 'usage_line': 765}, {'reason_category': 'Loop Body', 'usage_line': 765}] | Variable 'rowIndex' used at line 764 is defined at line 764 and has a Short-Range dependency.
Variable 'numRows' used at line 764 is defined at line 761 and has a Short-Range dependency.
Variable 'colIndex' used at line 765 is defined at line 765 and has a Short-Range dependency.
Variable 'numCols' used at line 765 is defined at line 760 and has a Short-Range dependency. | {'Define Stop Criteria': 2, 'Loop Body': 1} | {'Variable Short-Range': 4} |
completion_java | DoubleMatrixTester | 767 | 772 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', ''] | [' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);'] | [' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 767}, {'reason_category': 'Loop Body', 'usage_line': 768}, {'reason_category': 'Loop Body', 'usage_line': 769}, {'reason_category': 'Loop Body', 'usage_line': 770}, {'reason_category': 'Loop Body', 'usage_line': 771}, {'reason_category': 'Loop Body', 'usage_line': 772}] | Variable 'actualMatrix' used at line 768 is defined at line 758 and has a Short-Range dependency.
Variable 'colIndex' used at line 768 is defined at line 765 and has a Short-Range dependency.
Variable 'rowIndex' used at line 768 is defined at line 764 and has a Short-Range dependency.
Variable 'checkThisMatrix' used at line 769 is defined at line 758 and has a Medium-Range dependency.
Variable 'rowIndex' used at line 769 is defined at line 764 and has a Short-Range dependency.
Variable 'colIndex' used at line 769 is defined at line 765 and has a Short-Range dependency.
Function 'checkCloseEnough' used at line 772 is defined at line 486 and has a Long-Range dependency.
Variable 'actual' used at line 772 is defined at line 769 and has a Short-Range dependency.
Variable 'expected' used at line 772 is defined at line 768 and has a Short-Range dependency. | {'Loop Body': 6} | {'Variable Short-Range': 7, 'Variable Medium-Range': 1, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 772 | 772 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix'] | [' checkCloseEnough(actual, expected);'] | [' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 772}] | Function 'checkCloseEnough' used at line 772 is defined at line 486 and has a Long-Range dependency.
Variable 'actual' used at line 772 is defined at line 769 and has a Short-Range dependency.
Variable 'expected' used at line 772 is defined at line 768 and has a Short-Range dependency. | {'Loop Body': 1} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 885 | 889 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error'] | [' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }'] | ['', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'matrix' used at line 886 is defined at line 882 and has a Short-Range dependency.
Variable 'colIndex' used at line 886 is defined at line 882 and has a Short-Range dependency.
Variable 'errorNotThrown' used at line 888 is defined at line 883 and has a Short-Range dependency. | {} | {'Variable Short-Range': 3} |
completion_java | DoubleMatrixTester | 961 | 967 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.'] | [' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }'] | ['', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'matrix' used at line 962 is defined at line 957 and has a Short-Range dependency.
Variable 'columnIndex' used at line 962 is defined at line 957 and has a Short-Range dependency.
Variable 'column' used at line 962 is defined at line 957 and has a Short-Range dependency.
Variable 'errorNotThrown' used at line 964 is defined at line 958 and has a Short-Range dependency.
Variable 'errorNotThrown' used at line 966 is defined at line 964 and has a Short-Range dependency. | {} | {'Variable Short-Range': 5} |
completion_java | DoubleMatrixTester | 1,037 | 1,041 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {'] | [' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;'] | [' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'matrix' used at line 1037 is defined at line 1032 and has a Short-Range dependency.
Variable 'rowIndex' used at line 1037 is defined at line 1032 and has a Short-Range dependency.
Variable 'row' used at line 1037 is defined at line 1032 and has a Short-Range dependency.
Variable 'errorNotThrown' used at line 1039 is defined at line 1033 and has a Short-Range dependency.
Variable 'errorNotThrown' used at line 1041 is defined at line 1039 and has a Short-Range dependency. | {} | {'Variable Short-Range': 5} |
completion_java | DoubleMatrixTester | 1,098 | 1,100 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);'] | [' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);'] | [' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'RowMajorDoubleMatrix' used at line 1098 is defined at line 405 and has a Long-Range dependency.
Class 'RowMajorDoubleMatrix' used at line 1099 is defined at line 405 and has a Long-Range dependency.
Class 'RowMajorDoubleMatrix' used at line 1100 is defined at line 405 and has a Long-Range dependency. | {} | {'Class Long-Range': 3} |
completion_java | DoubleMatrixTester | 1,109 | 1,112 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices'] | [' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);'] | [' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'ColumnMajorDoubleMatrix' used at line 1109 is defined at line 355 and has a Long-Range dependency.
Class 'ColumnMajorDoubleMatrix' used at line 1110 is defined at line 355 and has a Long-Range dependency.
Class 'ColumnMajorDoubleMatrix' used at line 1111 is defined at line 355 and has a Long-Range dependency.
Class 'ColumnMajorDoubleMatrix' used at line 1112 is defined at line 355 and has a Long-Range dependency. | {} | {'Class Long-Range': 4} |
completion_java | DoubleMatrixTester | 1,135 | 1,136 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {'] | [' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);'] | [' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1135}, {'reason_category': 'Loop Body', 'usage_line': 1136}] | Variable 'j' used at line 1135 is defined at line 1133 and has a Short-Range dependency.
Variable 'i' used at line 1135 is defined at line 1132 and has a Short-Range dependency.
Variable 'checkMe' used at line 1136 is defined at line 1126 and has a Short-Range dependency.
Variable 'j' used at line 1136 is defined at line 1133 and has a Short-Range dependency.
Variable 'i' used at line 1136 is defined at line 1132 and has a Short-Range dependency.
Variable 'entry' used at line 1136 is defined at line 1135 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 6} |
completion_java | DoubleMatrixTester | 1,147 | 1,148 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {'] | [' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));'] | [' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1147}, {'reason_category': 'Loop Body', 'usage_line': 1148}] | Variable 'j' used at line 1147 is defined at line 1145 and has a Short-Range dependency.
Variable 'i' used at line 1147 is defined at line 1144 and has a Short-Range dependency.
Variable 'entry' used at line 1148 is defined at line 1147 and has a Short-Range dependency.
Variable 'checkMe' used at line 1148 is defined at line 1126 and has a Medium-Range dependency.
Variable 'j' used at line 1148 is defined at line 1145 and has a Short-Range dependency.
Variable 'i' used at line 1148 is defined at line 1144 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 5, 'Variable Medium-Range': 1} |
completion_java | DoubleMatrixTester | 1,170 | 1,171 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");'] | [' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);'] | [' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Class 'ColumnMajorDoubleMatrix' used at line 1170 is defined at line 355 and has a Long-Range dependency.
Function 'sparseMatrixLargeTester' used at line 1171 is defined at line 1126 and has a Long-Range dependency.
Variable 'cMatrix' used at line 1171 is defined at line 1170 and has a Short-Range dependency. | {} | {'Class Long-Range': 1, 'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 1,205 | 1,205 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)'] | [' changeRows[2] = numRows - 1;'] | [' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1205}] | Variable 'numRows' used at line 1205 is defined at line 1199 and has a Short-Range dependency.
Variable 'changeRows' used at line 1205 is defined at line 1203 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 1,210 | 1,210 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)'] | [' changeCols[2] = numCols - 1;'] | [' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1210}] | Variable 'numCols' used at line 1210 is defined at line 1200 and has a Short-Range dependency.
Variable 'changeCols' used at line 1210 is defined at line 1208 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleMatrixTester | 1,229 | 1,231 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix'] | [' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);'] | [' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1229}, {'reason_category': 'Loop Body', 'usage_line': 1230}, {'reason_category': 'Loop Body', 'usage_line': 1231}] | Class 'ColumnMajorDoubleMatrix' used at line 1229 is defined at line 355 and has a Long-Range dependency.
Variable 'numRows' used at line 1229 is defined at line 1199 and has a Medium-Range dependency.
Variable 'numCols' used at line 1229 is defined at line 1200 and has a Medium-Range dependency.
Variable 'myMatrix' used at line 1229 is defined at line 1224 and has a Short-Range dependency.
Variable 'numCols' used at line 1230 is defined at line 1200 and has a Medium-Range dependency.
Variable 'testVal' used at line 1230 is defined at line 1216 and has a Medium-Range dependency.
Variable 'setRow' used at line 1230 is defined at line 1225 and has a Short-Range dependency.
Function 'testSetRowEntryCombo' used at line 1231 is defined at line 1416 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1231 is defined at line 1229 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1231 is defined at line 1221 and has a Short-Range dependency.
Variable 'change_j_Entry' used at line 1231 is defined at line 1222 and has a Short-Range dependency.
Variable 'changeRow' used at line 1231 is defined at line 1219 and has a Medium-Range dependency.
Variable 'changeVal' used at line 1231 is defined at line 1217 and has a Medium-Range dependency.
Variable 'setRow' used at line 1231 is defined at line 1230 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Medium-Range': 6, 'Variable Short-Range': 6, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,234 | 1,236 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix'] | [' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);'] | [' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1234}, {'reason_category': 'Loop Body', 'usage_line': 1235}, {'reason_category': 'Loop Body', 'usage_line': 1236}] | Class 'RowMajorDoubleMatrix' used at line 1234 is defined at line 405 and has a Long-Range dependency.
Variable 'numRows' used at line 1234 is defined at line 1199 and has a Long-Range dependency.
Variable 'numCols' used at line 1234 is defined at line 1200 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1234 is defined at line 1229 and has a Short-Range dependency.
Variable 'numCols' used at line 1235 is defined at line 1200 and has a Long-Range dependency.
Variable 'testVal' used at line 1235 is defined at line 1216 and has a Medium-Range dependency.
Variable 'setRow' used at line 1235 is defined at line 1230 and has a Short-Range dependency.
Function 'testSetEntryRowCombo' used at line 1236 is defined at line 1375 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1236 is defined at line 1234 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1236 is defined at line 1221 and has a Medium-Range dependency.
Variable 'change_j_Entry' used at line 1236 is defined at line 1222 and has a Medium-Range dependency.
Variable 'changeRow' used at line 1236 is defined at line 1219 and has a Medium-Range dependency.
Variable 'changeVal' used at line 1236 is defined at line 1217 and has a Medium-Range dependency.
Variable 'setRow' used at line 1236 is defined at line 1235 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Long-Range': 3, 'Variable Short-Range': 4, 'Variable Medium-Range': 5, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,239 | 1,241 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix'] | [' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);'] | [' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1239}, {'reason_category': 'Loop Body', 'usage_line': 1240}, {'reason_category': 'Loop Body', 'usage_line': 1241}] | Class 'RowMajorDoubleMatrix' used at line 1239 is defined at line 405 and has a Long-Range dependency.
Variable 'numRows' used at line 1239 is defined at line 1199 and has a Long-Range dependency.
Variable 'numCols' used at line 1239 is defined at line 1200 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1239 is defined at line 1234 and has a Short-Range dependency.
Variable 'numCols' used at line 1240 is defined at line 1200 and has a Long-Range dependency.
Variable 'testVal' used at line 1240 is defined at line 1216 and has a Medium-Range dependency.
Variable 'setRow' used at line 1240 is defined at line 1235 and has a Short-Range dependency.
Function 'testSetRowEntryCombo' used at line 1241 is defined at line 1416 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1241 is defined at line 1239 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1241 is defined at line 1221 and has a Medium-Range dependency.
Variable 'change_j_Entry' used at line 1241 is defined at line 1222 and has a Medium-Range dependency.
Variable 'changeRow' used at line 1241 is defined at line 1219 and has a Medium-Range dependency.
Variable 'changeVal' used at line 1241 is defined at line 1217 and has a Medium-Range dependency.
Variable 'setRow' used at line 1241 is defined at line 1240 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Long-Range': 3, 'Variable Short-Range': 4, 'Variable Medium-Range': 5, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,260 | 1,262 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix'] | [' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);'] | [' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1260}, {'reason_category': 'Loop Body', 'usage_line': 1261}, {'reason_category': 'Loop Body', 'usage_line': 1262}] | Class 'ColumnMajorDoubleMatrix' used at line 1260 is defined at line 355 and has a Long-Range dependency.
Variable 'numRows' used at line 1260 is defined at line 1199 and has a Long-Range dependency.
Variable 'numCols' used at line 1260 is defined at line 1200 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1260 is defined at line 1191 and has a Long-Range dependency.
Variable 'numRows' used at line 1261 is defined at line 1199 and has a Long-Range dependency.
Variable 'testVal' used at line 1261 is defined at line 1252 and has a Short-Range dependency.
Variable 'setCol' used at line 1261 is defined at line 1193 and has a Long-Range dependency.
Function 'testSetEntryColCombo' used at line 1262 is defined at line 1455 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1262 is defined at line 1260 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1262 is defined at line 1257 and has a Short-Range dependency.
Variable 'change_j_Entry' used at line 1262 is defined at line 1258 and has a Short-Range dependency.
Variable 'changeCol' used at line 1262 is defined at line 1255 and has a Short-Range dependency.
Variable 'changeVal' used at line 1262 is defined at line 1253 and has a Short-Range dependency.
Variable 'setCol' used at line 1262 is defined at line 1261 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Long-Range': 5, 'Variable Short-Range': 7, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,265 | 1,267 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix'] | [' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);'] | [' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1265}, {'reason_category': 'Loop Body', 'usage_line': 1266}, {'reason_category': 'Loop Body', 'usage_line': 1267}] | Class 'ColumnMajorDoubleMatrix' used at line 1265 is defined at line 355 and has a Long-Range dependency.
Variable 'numRows' used at line 1265 is defined at line 1199 and has a Long-Range dependency.
Variable 'numCols' used at line 1265 is defined at line 1200 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1265 is defined at line 1260 and has a Short-Range dependency.
Variable 'numRows' used at line 1266 is defined at line 1199 and has a Long-Range dependency.
Variable 'testVal' used at line 1266 is defined at line 1252 and has a Medium-Range dependency.
Variable 'setCol' used at line 1266 is defined at line 1261 and has a Short-Range dependency.
Function 'testSetColEntryCombo' used at line 1267 is defined at line 1496 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1267 is defined at line 1265 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1267 is defined at line 1257 and has a Short-Range dependency.
Variable 'change_j_Entry' used at line 1267 is defined at line 1258 and has a Short-Range dependency.
Variable 'changeCol' used at line 1267 is defined at line 1255 and has a Medium-Range dependency.
Variable 'changeVal' used at line 1267 is defined at line 1253 and has a Medium-Range dependency.
Variable 'setCol' used at line 1267 is defined at line 1266 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Long-Range': 3, 'Variable Short-Range': 6, 'Variable Medium-Range': 3, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,275 | 1,277 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix'] | [' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);'] | [' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 1275}, {'reason_category': 'Loop Body', 'usage_line': 1276}, {'reason_category': 'Loop Body', 'usage_line': 1277}] | Class 'RowMajorDoubleMatrix' used at line 1275 is defined at line 405 and has a Long-Range dependency.
Variable 'numRows' used at line 1275 is defined at line 1199 and has a Long-Range dependency.
Variable 'numCols' used at line 1275 is defined at line 1200 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1275 is defined at line 1270 and has a Short-Range dependency.
Variable 'numRows' used at line 1276 is defined at line 1199 and has a Long-Range dependency.
Variable 'testVal' used at line 1276 is defined at line 1252 and has a Medium-Range dependency.
Variable 'setCol' used at line 1276 is defined at line 1271 and has a Short-Range dependency.
Function 'testSetColEntryCombo' used at line 1277 is defined at line 1496 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1277 is defined at line 1275 and has a Short-Range dependency.
Variable 'change_i_Entry' used at line 1277 is defined at line 1257 and has a Medium-Range dependency.
Variable 'change_j_Entry' used at line 1277 is defined at line 1258 and has a Medium-Range dependency.
Variable 'changeCol' used at line 1277 is defined at line 1255 and has a Medium-Range dependency.
Variable 'changeVal' used at line 1277 is defined at line 1253 and has a Medium-Range dependency.
Variable 'setCol' used at line 1277 is defined at line 1276 and has a Short-Range dependency. | {'Loop Body': 3} | {'Class Long-Range': 1, 'Variable Long-Range': 3, 'Variable Short-Range': 4, 'Variable Medium-Range': 5, 'Function Long-Range': 1} |
completion_java | DoubleMatrixTester | 1,389 | 1,389 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {'] | [' correct_val = row_val.getItem(i_entry);'] | [' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 1389}] | Variable 'row_val' used at line 1389 is defined at line 1375 and has a Medium-Range dependency.
Variable 'i_entry' used at line 1389 is defined at line 1375 and has a Medium-Range dependency.
Variable 'correct_val' used at line 1389 is defined at line 1384 and has a Short-Range dependency. | {'If Body': 1} | {'Variable Medium-Range': 2, 'Variable Short-Range': 1} |
completion_java | DoubleMatrixTester | 1,392 | 1,392 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.'] | [' correct_row = row_val;'] | [' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'row_val' used at line 1392 is defined at line 1375 and has a Medium-Range dependency.
Variable 'correct_row' used at line 1392 is defined at line 1377 and has a Medium-Range dependency. | {} | {'Variable Medium-Range': 2} |
completion_java | DoubleMatrixTester | 1,395 | 1,396 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here'] | [' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);'] | [' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'myMatrix' used at line 1395 is defined at line 1375 and has a Medium-Range dependency.
Variable 'j_entry' used at line 1395 is defined at line 1375 and has a Medium-Range dependency.
Variable 'i_entry' used at line 1395 is defined at line 1375 and has a Medium-Range dependency.
Variable 'entry_val' used at line 1395 is defined at line 1375 and has a Medium-Range dependency.
Variable 'myMatrix' used at line 1396 is defined at line 1375 and has a Medium-Range dependency.
Variable 'j_row' used at line 1396 is defined at line 1375 and has a Medium-Range dependency.
Variable 'row_val' used at line 1396 is defined at line 1375 and has a Medium-Range dependency. | {} | {'Variable Medium-Range': 7} |
completion_java | DoubleMatrixTester | 1,427 | 1,428 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here'] | [' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);'] | [' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Variable 'myMatrix' used at line 1427 is defined at line 1416 and has a Medium-Range dependency.
Variable 'j_row' used at line 1427 is defined at line 1416 and has a Medium-Range dependency.
Variable 'row_val' used at line 1427 is defined at line 1416 and has a Medium-Range dependency.
Variable 'myMatrix' used at line 1428 is defined at line 1416 and has a Medium-Range dependency.
Variable 'j_entry' used at line 1428 is defined at line 1416 and has a Medium-Range dependency.
Variable 'i_entry' used at line 1428 is defined at line 1416 and has a Medium-Range dependency.
Variable 'entry_val' used at line 1428 is defined at line 1416 and has a Medium-Range dependency. | {} | {'Variable Medium-Range': 7} |
completion_java | DoubleMatrixTester | 1,433 | 1,433 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {'] | [' correct_row.setItem(i_entry, entry_val);'] | [' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 1433}] | Variable 'correct_row' used at line 1433 is defined at line 1424 and has a Short-Range dependency.
Variable 'i_entry' used at line 1433 is defined at line 1416 and has a Medium-Range dependency.
Variable 'entry_val' used at line 1433 is defined at line 1416 and has a Medium-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 1, 'Variable Medium-Range': 2} |
completion_java | DoubleMatrixTester | 1,437 | 1,438 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.*;', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', '/**', ' * This interface corresponds to a sparse implementation of a matrix', ' * of double-precision values.', ' */', 'interface IDoubleMatrix {', ' ', ' /** ', ' * This returns the i^th row in the matrix. Note that the row that', ' * is returned may contain one or more references to data that are', ' * actually contained in the matrix, so if the caller modifies this', ' * row, it could end up modifying the row in the underlying matrix in', ' * an unpredicatble way. If i exceeds the number of rows in the matrix', ' * or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getRow (int i) throws OutOfBoundsException;', ' ', ' /** ', ' * This returns the j^th column in the matrix. All of the comments', ' * above regarding getRow apply. If j exceeds the number of columns in the', ' * matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' IDoubleVector getColumn (int j) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the i^th row of the matrix. After the row is inserted into', ' * the matrix, the matrix "owns" the row and it is free to do whatever it', ' * wants to it, including modifying the row. If i exceeds the number of rows', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setRow (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * This sets the j^th column of the matrix. All of the comments above for', ' * the "setRow" method apply to "setColumn". If j exceeds the number of columns', ' * in the matrix or it is less than zero, an OutOfBoundsException is thrown.', ' */', ' void setColumn (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Returns the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' double getEntry (int i, int j) throws OutOfBoundsException;', ' ', ' /**', ' * Sets the entry in the i^th row and j^th column in the matrix.', ' * If i or j are less than zero, or if j exceeds the number of columns', ' * or i exceeds the number of rows, then an OutOfBoundsException is thrown.', ' */', ' void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' ', ' /**', ' * Adds this particular IDoubleMatrix to the parameter. Returns an', " * OutOfBoundsException if the two don't match up in terms of their dimensions.", ' */', ' void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException;', '', ' /** ', ' * Sums all of the rows of this IDoubleMatrix. It is the equivalent of saying:', ' *', ' * SparseDoubleVector accum = new SparseDoubleVector (myMatrix.getNumColumns (), 0.0);', ' * for (int i = 0; i < myMatrix.getNumRows (); i++) {', ' * myMatrix.getRow (i).addMyselfToHim (accum);', ' * }', ' * return accum;', ' *', ' * Note, however, that the implementation should be more efficient than this if you', ' * have a row major matrix... then, it should run on O(m) time, where m is the number', ' * of non-empty rows.', ' */', ' IDoubleVector sumRows ();', '', ' /**', ' * Sums all of the columns of this IDoubleMatrix. Returns the result.', ' */', ' IDoubleVector sumColumns ();', '', ' /**', ' * Returns the number of rows in the matrix.', ' */', ' int getNumRows ();', ' ', ' /**', ' * Returns the number of columns in the matrix.', ' */', ' int getNumColumns ();', ' ', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', 'abstract class ADoubleMatrix implements IDoubleMatrix {', ' ', ' /**', ' * The basic idea here is to put everything in the anstract class. Then the two', ' * concrete classes (row major and column major) just call these functions... the', ' * only difference between row major and column major is that they call different', ' * operations', ' */', ' private ISparseArray <IDoubleVector> myData;', ' private int numCols;', ' private int numRows;', ' private double backValue;', ' ', ' protected ADoubleMatrix (int numRowsIn, int numColsIn, double backValueIn) {', ' numCols = numColsIn;', ' numRows = numRowsIn;', ' backValue = backValueIn;', ' myData = new LinearSparseArray <IDoubleVector> (10);', ' if (numCols < 0 || numRows < 0)', ' throw new RuntimeException ("Bad input index");', ' }', ' ', ' protected IDoubleVector getRowABS (int j) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getRowABS");', ' ', ' IDoubleVector returnVal = myData.get (j);', ' if (returnVal == null) {', ' returnVal = new SparseDoubleVector (numCols, backValue); ', ' }', ' return returnVal;', ' }', ' ', ' protected IDoubleVector getColumnABS (int i) throws OutOfBoundsException {', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getColABS");', ' ', ' IDoubleVector returnVal = new SparseDoubleVector (numRows, backValue);', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow != null) {', ' returnVal.setItem (row, myRow.getItem (i));', ' }', ' }', ' return returnVal;', ' }', ' ', ' protected void setRowABS (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0 || setToMe.getLength () != numCols)', ' throw new OutOfBoundsException ("row out of bounds in setRowABS");', ' myData.put (j, setToMe);', ' }', ' ', ' protected void setColumnABS (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' if (i >= numCols || i < 0 || setToMe.getLength () != numRows)', ' throw new OutOfBoundsException ("col out of bounds in setColumnABS");', ' ', ' for (int row = 0; row < numRows; row++) {', ' IDoubleVector myRow = myData.get (row);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (row, myRow);', ' }', ' myRow.setItem (i, setToMe.getItem (row));', ' } ', ' }', ' ', ' protected double getEntryABS (int j, int i) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in getEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in getEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' return backValue; ', ' }', ' return myRow.getItem (i);', ' }', ' ', ' public IDoubleVector sumRows () {', ' IDoubleVector sum = new DenseDoubleVector (getNumColumns (), 0.0);', ' for (int i = 0; i < getNumRows (); i++) {', ' try {', ' IDoubleVector curRow = getRow (i);', ' curRow.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' public IDoubleVector sumColumns () {', ' IDoubleVector sum = new DenseDoubleVector (getNumRows (), 0.0);', ' for (int i = 0; i < getNumColumns (); i++) {', ' try {', ' IDoubleVector curCol = getColumn (i);', ' curCol.addMyselfToHim (sum);', ' } catch (OutOfBoundsException e) {throw new RuntimeException (e);}', ' }', ' return sum;', ' }', ' ', ' protected void setEntryABS (int j, int i, double setToMe) throws OutOfBoundsException {', ' if (j >= numRows || j < 0)', ' throw new OutOfBoundsException ("row out of bounds in setEntryABS");', ' if (i >= numCols || i < 0)', ' throw new OutOfBoundsException ("col out of bounds in setEntryABS");', ' IDoubleVector myRow = myData.get (j);', ' if (myRow == null) {', ' myRow = new SparseDoubleVector (numCols, backValue);', ' myData.put (j, myRow);', ' }', ' myRow.setItem (i, setToMe);', ' }', ' ', ' protected int getNumRowsABS () {', ' return numRows;', ' }', ' ', ' protected int getNumColumnsABS () {', ' return numCols;', ' }', ' ', ' /**', ' * Theare are the various operations that will be implemented in the concrete classes', ' */', ' abstract public IDoubleVector getRow (int j) throws OutOfBoundsException;', ' abstract public IDoubleVector getColumn (int i) throws OutOfBoundsException;', ' abstract public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException;', ' abstract public double getEntry (int i, int j) throws OutOfBoundsException;', ' abstract public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException;', ' abstract public int getNumRows ();', ' abstract public int getNumColumns ();', '}', '', '', 'class ColumnMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public ColumnMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numCols, numRows, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getColumnABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getRowABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numCols = getNumColumns ();', ' for (int i = 0; i < numCols; i++) {', ' IDoubleVector curCol = getColumn (i);', ' IDoubleVector hisCol = toMe.getColumn (i);', ' curCol.addMyselfToHim (hisCol);', ' toMe.setColumn (i, hisCol);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (j, i); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (j, i, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumColumnsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumRowsABS ();', ' }', '}', '', '', 'class RowMajorDoubleMatrix extends ADoubleMatrix {', ' ', ' public RowMajorDoubleMatrix (int numRows, int numCols, double defaultVal) {', ' super (numRows, numCols, defaultVal); ', ' }', ' ', ' public IDoubleVector getRow (int j) throws OutOfBoundsException {', ' return getRowABS (j); ', ' }', ' ', ' public IDoubleVector getColumn (int i) throws OutOfBoundsException {', ' return getColumnABS (i); ', ' }', ' ', ' public void setRow (int j, IDoubleVector setToMe) throws OutOfBoundsException {', ' setRowABS (j, setToMe); ', ' }', ' ', ' public void addMyselfToHim (IDoubleMatrix toMe) throws OutOfBoundsException {', ' int numRows = getNumRows ();', ' for (int i = 0; i < numRows; i++) {', ' IDoubleVector curRow = getRow (i);', ' IDoubleVector hisRow = toMe.getRow (i);', ' curRow.addMyselfToHim (hisRow);', ' toMe.setRow (i, hisRow);', ' }', ' }', ' ', ' public void setColumn (int i, IDoubleVector setToMe) throws OutOfBoundsException {', ' setColumnABS (i, setToMe); ', ' }', ' ', ' public double getEntry (int i, int j) throws OutOfBoundsException {', ' return getEntryABS (i, j); ', ' }', ' ', ' public void setEntry (int i, int j, double setToMe) throws OutOfBoundsException {', ' setEntryABS (i, j, setToMe);', ' }', ' ', ' public int getNumRows () {', ' return getNumRowsABS (); ', ' }', ' ', ' public int getNumColumns () {', ' return getNumColumnsABS ();', ' }', '}', '/**', ' * A JUnit test case class for testing an implementation of an IDoubleMatrix. Every method starting with the word "test" will be called when running the test with JUnit.', ' */', 'public class DoubleMatrixTester extends TestCase {', '// Constants to contain the boundary values we will test for.', ' private final double MAX_DOUBLE = Double.MAX_VALUE;', ' private final double MIN_DOUBLE = Double.MIN_VALUE;', ' private final double POSITIVE_INFINITY = Double.POSITIVE_INFINITY;', ' private final double NEGATIVE_INFINITY = Double.NEGATIVE_INFINITY;', ' ', ' // An array of doubles of test values that we test every method on. These include the boundary values from above, 0.0, average values, decimals, negative, maximum, minimum, positive and negative inifinity.', ' private final double[] testValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE, POSITIVE_INFINITY, NEGATIVE_INFINITY};', ' // An array of doubles of initial values that we test every method on. These include the boundary values from above, 0.0, average values, and decimals.', ' // Note that Positive and Negative infinity is excluded here. This is due to a problem with the initialization of SparseDoubleVectors. If we initialize a ', ' // sparse double vector with infinity, changing it from infinity will result in NaN. Note that NaN compared to NaN always results in false.', ' private final double[] initValues = {0.0, 1.0, -1.0, -100.0, 100.0, 15.1610912461267127317, -2372.3616123612361237132, MAX_DOUBLE, MIN_DOUBLE}; ', ' ', ' // Here, we have a different set of values for the "set values". We have to use these values as opposed to the init values above due to precision and boundary issues.', ' // For the boundary issues, when we utilize MAX_DOUBLE, but then set a value to a negative number, the SpareDoubleVector will store a number that is less than the minimum possible number', ' // at this point. This will result in an overflow, and loop back around to 0. A similar thing happens with MIN_DOUBLE and positive values.', ' // On the other hand, when we test with numbers with many decimals, this leads to losses in precision when we set values. Therefore, these small losses in precision will evaluate', ' // to a miss when we compare it. ', ' private final double[] setValues = {0.0, -1.0, -6000000.0, 5000000000000.0}; ', ' // An array of integers that represent indices we utilize when testing for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] failIndices = {-100, -1, 1000};', ' // An array of integers that represent indices that work when we test for failures (when we are catching OutOfBoundaryExceptions)', ' private final int[] validIndices = {0, 99};', ' // An array of integers that represent lengths of columns [rows] that would not be accepted by an array of height [length] 100.', ' private final int[] failLengths = {1, 99, 1000};', ' /**', ' * This is used all over the place to check if an observed value is close', ' * enough to an expected double value', ' */', ' private void checkCloseEnough(double observed, double goal) {', ' if (!(observed > goal - 0.000001 && ', ' observed < goal + 0.000001)) {', ' fail("Got " + observed + ", expected " + goal);', ' }', ' }', ' ', ' /**', " * Tests that the matrix's size (number of columns, number of rows) is set properly.", ' */', ' public void testMatrixSize() {', ' ', ' for (int i = 0; i < 100; i += 10) {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Row major matrix size (col) failed to match", i, rMatrix.getNumColumns());', ' assertEquals("Row major matrix size (rows) failed to match", i*2, rMatrix.getNumRows());', '', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(i*2, i, 5.0);', ' assertEquals("Column major matrix size (col) failed to match", i, cMatrix.getNumColumns());', ' assertEquals("Column major matrix size (rows) failed to match", i*2, cMatrix.getNumRows());', ' }', ' ', ' throwsCorrectExceptionWithInitialization(-1, 5);', ' throwsCorrectExceptionWithInitialization(5, -1);', ' throwsCorrectExceptionWithInitialization(-3, -3);', ' }', ' ', ' /**', " * Tests if the matrix's constructor does its job properly with guaranteeing valid inputs for ", ' * the number of columns and number of rows.', ' * Precondition: numCols or numRows should be invalid (less than 0)', ' * ', ' * @param numCols number of columns in the matrix to initialize', ' * @param numRows number of rows in the matrix to initialize', ' */', ' private void throwsCorrectExceptionWithInitialization(int numCols, int numRows) {', ' boolean errorNotThrown = true;', ' ', ' try {', ' // try to initialize matrices of invalid proportions, which should throw an exception', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' } catch (Exception e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Test that every element of a newly initialized matrix has the same initial value.', ' */', ' public void testMatrixInitialValue() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 3, 5.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 3, 5.0);', ' ', ' checkAllMatrixElementsEqualTo(rMatrix, 3, 4, 5.0);', ' checkAllMatrixElementsEqualTo(cMatrix, 3, 4, 5.0);', ' }', ' ', ' /**', ' * Checks that all elements of a matrix are equal to the same value.', ' * @param matrix - matrix to be checked', ' * @param numCols - number of columns of the matrix', ' * @param numRows - number of rows of the matrix', ' * @param sameValue - value that all elements of the matrix should be equal to', ' */', ' private void checkAllMatrixElementsEqualTo(IDoubleMatrix matrix, int numCols, int numRows, double sameValue) {', ' for (int i = 0; i < numCols; i++) {', ' for (int j = 0; j < numRows; j++) {', ' try {', ' if (matrix.getEntry(j, i) != sameValue) {', ' fail("The initial value of the matrix was not set correctly.");', ' }', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Helper method that tests if a primitive array and an IDoubleVector have the same elements.', ' * Makes use of checkCloseEnough to do the comparison between doubles.', ' * @param expected array of expected values', ' * @param actual IDoubleVector of actual values', ' */', ' private void checkListsAreEqual(double[] expected, IDoubleVector actual) {', ' for (int i = 0; i < expected.length; i++) {', ' try {', ' checkCloseEnough(actual.getItem(i), expected[i]);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' ', ' /**', ' * Tests a simple setting and getting n a matrix.', ' */', ' public void testSimpleSetAndGet() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' trySimpleSetAndGetOnMatrix(rMatrix);', ' trySimpleSetAndGetOnMatrix(cMatrix);', ' }', '', ' /**', ' * Used to test a simple setting and getting of an element in a matrix.', ' * Checks for out-of-bounds access as well.', ' * @param matrix matrix to be tested', ' */', ' public void trySimpleSetAndGetOnMatrix(IDoubleMatrix matrix) {', ' try {', ' // is a valid entry index (colNum, rowNum) - this operation shuold succeed', ' matrix.setEntry(5, 6, 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid set operation.");', ' }', ' ', ' // check out of bounds accesses on both dimensions with setEntry()', ' throwsCorrectExceptionWithSet(matrix, -10, 5, 100);', ' throwsCorrectExceptionWithSet(matrix, 5, -10, 100);', ' throwsCorrectExceptionWithSet(matrix, 17, 6, 100); ', ' throwsCorrectExceptionWithSet(matrix, 6, 17, 100);', ' ', ' try {', ' checkCloseEnough(matrix.getEntry(5, 6), 9999);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', '', ' }', ' ', ' // check out of bounds accesses on both dimensions with getEntry()', ' throwsCorrectExceptionWithGet(matrix, -10, 5);', ' throwsCorrectExceptionWithGet(matrix, 5, -10);', ' throwsCorrectExceptionWithGet(matrix, 17, 6); ', ' throwsCorrectExceptionWithGet(matrix, 6, 17);', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with setEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' * @param value value to set the specified test entry as', ' */', ' private void throwsCorrectExceptionWithSet(IDoubleMatrix matrix, int i, int j, double value) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.setEntry(j, i, value);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid index is accessed in the given matrix', ' * with getEntry().', ' * Precondition: should be called with indices that are out of bounds for the given matrix,', ' * as defined in the specification.', ' * @param matrix', ' * @param i column in matrix to be accessed', ' * @param j row in matrix to be accessed', ' */', ' private void throwsCorrectExceptionWithGet(IDoubleMatrix matrix, int i, int j) {', ' boolean errorNotThrown = true;', ' // try to set entry at an invalid set of indexes; setEntry should throw an error', ' try {', ' matrix.getEntry(j, i);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests that multiple elements can be rewritten in the matrix ', ' * multiple times.', ' */', ' public void testRewriteMatrix() {', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(10, 10, 1.0);', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(10, 10, 1.0);', '', ' // fill the matrices with simple values', ' simpleInitializeMatrix(rMatrix);', ' simpleInitializeMatrix(cMatrix);', ' ', ' // check that matrix elements have been set correctly after initial rewrite', ' double[][] primitiveMatrix = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};', ' checkEquivalence(primitiveMatrix, rMatrix);', ' checkEquivalence(primitiveMatrix, cMatrix);', ' ', ' // then rewrite elements again', ' simpleInitializeMatrix(rMatrix, 2);', ' simpleInitializeMatrix(cMatrix, 2);', ' ', ' // check that matrix elements have been set correctly after second rewrite', ' double[][] expectedMatrix = {{2,3,4},{5,6,7},{8,9,10},{11,12,13}};', ' checkEquivalence(expectedMatrix, rMatrix);', ' checkEquivalence(expectedMatrix, cMatrix);', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * counter counter+3 counter+6 counter+9', ' * ', ' * counter+1 counter+4 counter+7 counter+10', ' * ', ' * counter+2 counter+5 counter+8 counter+11', ' * ', ' * Preconditions: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix, int counter) {', ' for (int i = 0; i < 4; i++) {', ' for (int j = 0; j < 3; j++) {', ' try {', ' // initialize matrix row-by-row, then column-by-column', ' matrix.setEntry(j, i, counter);', ' // increment counter so that matrix elements are different, but predictable', ' counter++;', ' } catch (OutOfBoundsException e) {', ' fail("Caught an unexpected OutOfBounds error when doing a valid setEntry.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Initializes a matrix to a set of simple values. Note that this only', ' * initializes the top left-hand 4 columns and 3 rows; all other elements', ' * are left unchanged. Top elements of matrix will look like: ', ' * 1.0 4.0 7.0 10.0', ' * ', ' * 2.0 5.0 8.0 11.0', ' * ', ' * 3.0 6.0 9.0 12.0', ' * ', ' * Precondition: matrix size is at least 4 col x 3 rows', ' * @param matrix', ' */', ' private void simpleInitializeMatrix(IDoubleMatrix matrix) {', ' simpleInitializeMatrix(matrix, 1);', ' }', ' ', ' /**', ' * Checks that all elements of a primitive 2-d array are equivalent to the elements found in a matrix.', ' * Note that if the matrix is larger than the primitive 2-d array, the elements in the matrix', ' * that do not have any corresponding elements in the 2-d array will not be checked', ' * ', ' * @param actualMatrix primitive matrix (specified in format of {{col},{col},{col}}', ' * @param checkThisMatrix', ' */', ' private void checkEquivalence(double[][] actualMatrix, IDoubleMatrix checkThisMatrix) {', ' // set up for iteration', ' int numCols = actualMatrix.length;', ' int numRows = actualMatrix[0].length;', ' ', ' // iterate through elements of 2-d array and matrix', ' for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {', ' for (int colIndex = 0; colIndex < numCols; colIndex++) {', '', ' try {', ' double expected = actualMatrix[colIndex][rowIndex];', ' double actual = checkThisMatrix.getEntry(rowIndex, colIndex);', ' ', ' // compare corresponding elements from the 2-d array and the IDoubleMatrix', ' checkCloseEnough(actual, expected);', ' } catch (OutOfBoundsException e) {', ' fail("Encountered an out of bounds exception when doing a valid get operation.");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests if the getRow() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 5, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetRowWorks(cMatrix, 5.0);', ' seeIfGetRowWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetRowWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetRow(matrix, 5);', ' throwsCorrectExceptionGetRow(matrix, -1);', ' ', ' try {', ' ', ' checkListsAreEqual(new double[]{1, 4, 7, 10, initialValue}, matrix.getRow(0));', ' checkListsAreEqual(new double[]{2, 5, 8, 11, initialValue}, matrix.getRow(1));', ' checkListsAreEqual(new double[]{3, 6, 9, 12, initialValue}, matrix.getRow(matrix.getNumRows()-1));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getRow() operatoin.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid row is accessed in the given matrix', ' * with getRow().', ' * Precondition: should be called with row index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param rowIndex', ' */', ' private void throwsCorrectExceptionGetRow(IDoubleMatrix matrix, int rowIndex) {', ' boolean errorNotThrown = true;', ' // try to get row at an invalid row index; getRow should throw an error', ' try {', ' matrix.getRow(rowIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the getColumn() function works correctly, also checks for out of bounds access errors.', ' */', ' public void testSimpleGetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(4, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(4, 4, 5.0);', ' ', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfGetColumnWorks(cMatrix, 5.0);', ' seeIfGetColumnWorks(rMatrix, 5.0);', ' }', ' ', ' /**', ' * Test if getColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access.', ' * ', ' * @param matrix', ' * @param initialValue the initial value of every element in the matrix', ' */', ' private void seeIfGetColumnWorks(IDoubleMatrix matrix, double initialValue) {', ' throwsCorrectExceptionGetColumn(matrix, 5);', ' throwsCorrectExceptionGetColumn(matrix, -1);', '', ' try {', ' checkListsAreEqual(new double[]{1, 2, 3, initialValue}, matrix.getColumn(0));', ' checkListsAreEqual(new double[]{4, 5, 6, initialValue}, matrix.getColumn(1));', ' checkListsAreEqual(new double[]{7, 8, 9, initialValue}, matrix.getColumn(2));', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid getColumn() operation.");', ' }', ' }', ' ', ' /**', ' * Checks that an exception is thrown when an invalid column is accessed in the given matrix', ' * with getColumn().', ' * Precondition: should be called with column index that is out of bounds for the given matrix,', ' * as defined in the specification.', '', ' * @param matrix', ' * @param colIndex', ' */', ' private void throwsCorrectExceptionGetColumn(IDoubleMatrix matrix, int colIndex) {', ' boolean errorNotThrown = true;', ' // try to get col at an invalid col index; getColumn should throw an error', ' try {', ' matrix.getColumn(colIndex);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' }', '', ' // if no error was detected, then fail the test', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests if the setColumn() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetColumn() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', ' ', ' // setup both matrices', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' // test both matrices', ' seeIfSetColumnWorks(cMatrix);', ' seeIfSetColumnWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setColumn() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setColumn() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetColumnWorks(IDoubleMatrix matrix) {', ' IDoubleVector column = new SparseDoubleVector(3, 9999.0);', ' IDoubleVector inappropriateLengthColumn = new SparseDoubleVector(100, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthColumn2 = new SparseDoubleVector(0, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid column indices are to be set, ', ' // or the IDoubleVector argument in setColumn is null', ' throwsCorrectExceptionSetColumn(matrix, 10, column);', ' throwsCorrectExceptionSetColumn(matrix, -1, column);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn);', ' throwsCorrectExceptionSetColumn(matrix, 2, inappropriateLengthColumn2);', '', ' try {', ' // try a valid case, see if column ends up matching the expected column of values', ' matrix.setColumn(2, column);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getColumn(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setColumn()/getColumn() operation.");', ' } ', ' }', '', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param columnIndex', ' * @param column', ' */', ' private void throwsCorrectExceptionSetColumn(IDoubleMatrix matrix, int columnIndex, IDoubleVector column) {', ' boolean errorNotThrown = true;', '', ' // try an invalid setColumn at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setColumn(columnIndex, column);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', '', ' /**', ' * Tests if the setRow() function works correctly, also checks for out of bounds access ', ' * or illegal argument errors which should be thrown under certain conditions.', ' */', ' public void testSetRow() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(3, 4, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(3, 4, 5.0);', '', ' simpleInitializeMatrix(cMatrix);', ' simpleInitializeMatrix(rMatrix);', ' ', ' seeIfSetRowWorks(cMatrix);', ' seeIfSetRowWorks(rMatrix);', ' }', ' ', ' /**', ' * Test if setRow() works as specified. Tests if OutOfBounds exceptions are ', ' * thrown correctly with invalid access; also tests if IllegalArgument exceptions', ' * are thrown when the IDoubleVector argument in setRow() is null or not of the same', ' * length as the columns of the matrix', ' * ', ' * @param matrix', ' */', ' private void seeIfSetRowWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(4, 9999.0);', ' IDoubleVector inappropriateLengthRow = new SparseDoubleVector(3, -Double.MAX_VALUE);', ' IDoubleVector inappropriateLengthRow2 = new SparseDoubleVector(5, -Double.MAX_VALUE);', ' ', ' // all of these cases should throw an exception - either invalid row indices are to be set, ', ' // or the IDoubleVector argument in setRow is null', ' throwsCorrectExceptionSetRow(matrix, 10, row);', ' throwsCorrectExceptionSetRow(matrix, -1, row);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow);', ' throwsCorrectExceptionSetRow(matrix, 2, inappropriateLengthRow2);', ' ', ' // check that the row was set correctly', ' try {', ' matrix.setRow(2, row);', ' checkListsAreEqual(new double[] {9999, 9999, 9999}, matrix.getRow(2));', '', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds when doing a valid setRow()/getRow() operation.");', ' }', ' }', ' ', ' /**', ' * Tests if OutOfBounds exceptions are thrown correctly with invalid access;', ' * also tests if IllegalArgument exceptions are thrown when the', ' * IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix.', ' * ', ' * Preconditions: IDoubleVector argument in setColumn() is null or not of the same length', ' * as the columns of the matrix or the column index exceeds the bounds of the matrix.', ' * ', ' * @param matrix', ' * @param rowIndex', ' * @param row', ' */', ' private void throwsCorrectExceptionSetRow(IDoubleMatrix matrix, int rowIndex, IDoubleVector row) {', ' boolean errorNotThrown = true;', ' ', ' // try an invalid setRow at either an invalid index or with an invalid (null) argument, which should throw an error.', ' try {', ' matrix.setRow(rowIndex, row);', ' } catch (OutOfBoundsException e) {', ' errorNotThrown = false;', ' } catch (IllegalArgumentException e) {', ' errorNotThrown = false;', ' }', '', ' if (errorNotThrown) {', ' fail("Was expecting an OutOfBounds or IllegalArgument exception to be thrown.");', ' }', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' */', ' public void testMoreComplexGetAndSet() {', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix(6, 5, 5.0);', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix(6, 5, 5.0);', '', ' seeIfComplexSetAndGetWorks(cMatrix);', ' seeIfComplexSetAndGetWorks(rMatrix);', ' }', ' ', ' /**', ' * Tests a more complex scenario of getting and setting columns and rows.', ' * Basically, see if overwriting an element in a column by setting a row works, and ', ' * see if overwriting an element in a row by setting a column works properly.', ' * @param matrix the matrix to be tested', ' */', ' private void seeIfComplexSetAndGetWorks(IDoubleMatrix matrix) {', ' IDoubleVector row = new SparseDoubleVector(5, 100.0);', ' ', ' IDoubleVector column = new SparseDoubleVector(6, -999.0);', ' IDoubleVector secondColumn = new SparseDoubleVector(6, 9999.0);', ' ', ' try {', ' // also serves as a black-box test: no elements have been initialized at all before', ' // the setColumn() and setRow() methods are called', ' matrix.setColumn(3, column);', ' matrix.setRow(3, row);', ' ', ' checkListsAreEqual(new double[]{-999, -999, -999, 100, -999, -999}, matrix.getColumn(3));', ' ', ' // now set another column, rewriting the value at the intersection of column 3 and row 3', ' matrix.setColumn(3, secondColumn);', ' checkListsAreEqual(new double[]{100, 100, 100, 9999, 100}, matrix.getRow(3));', ' ', ' // check that getEntry returns the correct result at the intersection of this changed row and column', ' checkCloseEnough(matrix.getEntry(3,3), 9999);', ' ', ' } catch (OutOfBoundsException e) {', ' fail("Went OutOfBounds on a valid row or column access.");', ' }', ' }', ' ', ' /**', ' * Tests access in boundary cases for matrices of various sizes - 0x0, 0x1, 1x0, and 1x1.', ' */', ' public void testBoundaryCases() {', ' // make 0x0, 0x1, 1x0, and 1x1 row-major matrices', ' IDoubleMatrix rMatrixSizeZero = new RowMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOneColumn = new RowMajorDoubleMatrix(0, 1, 0.0); ', ' IDoubleMatrix rMatrixSizeOneRow = new RowMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix rMatrixSizeOne = new RowMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(rMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(rMatrixSizeOne, 1, 1);', ' ', ' // make 0x0, 0x1, 1x0, and 1x1 column-major matrices', ' IDoubleMatrix cMatrixSizeZero = new ColumnMajorDoubleMatrix(0, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOneColumn = new ColumnMajorDoubleMatrix(0, 1, 0.0);', ' IDoubleMatrix cMatrixSizeOneRow = new ColumnMajorDoubleMatrix(1, 0, 0.0);', ' IDoubleMatrix cMatrixSizeOne = new ColumnMajorDoubleMatrix(1, 1, 0.0);', ' ', ' // test that any accesses with get entry will produce an OutOfBoundsException', ' throwsCorrectExceptionWithGet(cMatrixSizeZero, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneColumn, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOneRow, 0, 0);', ' throwsCorrectExceptionWithGet(cMatrixSizeOne, 1, 1);', ' }', ' ', ' ', ' /**', ' * Tests the matrix by writing few entries in a really large matrix.', ' * The dimensions of the matrix should preferably be atleast 500x500.', ' */', ' private void sparseMatrixLargeTester (IDoubleMatrix checkMe) {', ' // Get dimensions', ' int numColumns = checkMe.getNumColumns();', ' int numRows = checkMe.getNumRows();', ' ', ' // Reset individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' checkMe.setEntry(j,i,entry);', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to set the entry column: " + i + " row: " + j);', ' }', ' }', ' }', '', ' // Get individual entries', ' for (int i = 0; i < numColumns; i+=100) {', ' for (int j = 0; j < numRows; j+=100) {', ' try {', ' double entry = (j+1)*10+(i+1);', ' assertEquals(entry, checkMe.getEntry(j,i));', ' } catch (OutOfBoundsException e) {', ' fail("Was unable to get the entry column: " + i + " row: " + j);', ' }', ' }', ' }', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseRowMajor () {', ' System.out.println("Testing sparse RowMajorDoubleMatrix.");', ' IDoubleMatrix rMatrix = new RowMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(rMatrix);', ' }', ' ', ' /**', ' * Tests the matrix by writing around 1% of the matrix in a sparse manner for a RowMajorDoubleMatrix', ' */', ' public void testSparseColumnMajor () {', ' System.out.println("Testing sparse ColumnMajorDoubleMatrix.");', ' IDoubleMatrix cMatrix = new ColumnMajorDoubleMatrix (1000,1000,-1.0);', ' sparseMatrixLargeTester(cMatrix);', ' }', ' ', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting an entry, then setting a row.', ' * setting an entry, then setting a column.', ' * setting a row, then setting an entry.', ' * setting a column, then setting an entry.', ' */', ' public void testEntryCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices (the sizes we mentioned above)', ' for (int i = 1; i < 1000; i = i * 10) {', ' for (int j = 0; j < 3; j++) {', ' for (int k = 0; k < 3; k++) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a row, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting an entry and then the row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetEntryRowCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' ', ' // Test setting a row and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' testSetRowEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeRow, changeVal, setRow);', ' }', ' }', ' }', ' }', ' }', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then an entry (or the other way around) on all possible combinations from ', " // a corner to a boundary, a boundary to a corner, or even middle cases. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) {', ' // Iterate through middle and corner entries.', ' for (int change_i_Entry : changeCols) {', ' for (int change_j_Entry : changeRows) {', ' // Test setting an entry and then the column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting an entry and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetEntryColCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' ', ' // Test setting a column and then the entry on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setCol = new SparseDoubleVector(numRows, testVal);', ' testSetColEntryCombo(myMatrix, change_i_Entry, change_j_Entry, changeCol, changeVal, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' }', ' ', ' /**', ' * This test runs a test on the following combinations on a wide variety of matrix sizes and indices. ', ' * Here, we test ', ' * setting a column, then setting a row.', ' * setting a row, then setting a column.', ' */', ' public void testColRowCombos () {', ' int numRows;', ' int numCols;', ' // Change rows represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeRows = {0, 0, 0};', ' // Change columns represents the row indices that we change to another value (distinct from the initial value)', ' int[] changeCols = {0, 0, 0};', ' double initVal = 0.0;', ' IDoubleMatrix myMatrix;', ' SparseDoubleVector setRow;', ' SparseDoubleVector setCol;', ' ', ' // Test for all size of matrices as mentioed above.', ' for (int i = 1; i < 1000; i = i * 1000) {', ' for (int j = 0; j < 3; j=j+2) {', ' for (int k = 0; k < 3; k=k+2) {', ' numRows = i + j * 100;', ' numCols = i + k * 100;', ' ', ' // We test a middle row index (middle case)', ' changeRows[1] = numRows / 2;', ' // We also test the last row index (boundary case)', ' changeRows[2] = numRows - 1;', ' ', ' // We test a middle column index (middle case)', ' changeCols[1] = numCols / 2;', ' // We also test the last column index (boundary case)', ' changeCols[2] = numCols - 1;', ' ', ' // We use values from setValues due to the reason we mention at the top. ', ' // Here, we test setting a column, then a row (or the other way around) on all possible combinations from ', " // a boundary to a boundary, or a boundary to a middle, to even middle to middle. We also verify that when they don't", ' // intersect, that it works as well.', ' for (double testVal : setValues) {', ' for (double changeVal : setValues) {', ' // Iterate through middle, top, and bottom rows', ' for (int changeRow : changeRows) {', ' // Iterate through middle, leftmost, and rightmost columns', ' for (int changeCol : changeCols) { ', ' // Test setting a row and then a column on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a column major double matrix', ' myMatrix = new ColumnMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a row and then the column on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testRowColCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' // Test setting a column and then a row on a row major double matrix', ' myMatrix = new RowMajorDoubleMatrix(numRows, numCols, 0.0);', ' setRow = new SparseDoubleVector(numCols, testVal);', ' setCol = new SparseDoubleVector(numRows, changeVal);', ' testColRowCombo(myMatrix, changeCol, changeRow, setRow, setCol);', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' }', ' ', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a row within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetEntryRowCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' ', ' // We wrap it in a try statement since if we catch an OutOfBoundsException, then something went wrong.', ' try {', ' // Set the correct value to be initially the entry value.', ' correct_val = entry_val;', ' // Note though that since we change the row later, if the row that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the row. ', ' // We account for that here by changing the correct value if that happens.', ' if (j_entry == j_row) {', ' correct_val = row_val.getItem(i_entry);', ' }', ' // The correct row is the row passed in since the row will never change.', ' correct_row = row_val;', ' ', ' // We set the entry and row here', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setRow(j_row, row_val);', ' // We then compare if it matches with what was expected.', ' testGetRow(myMatrix, j_row, correct_row);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Here, we test first setting a row in the matrix, then setting an entry within the matrix. ', ' * We check that the row is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param j_row The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param row_val the row that we will setRow with', ' */', ' private void testSetRowEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int j_row, double entry_val, IDoubleVector row_val) {', ' // An IDoubleVector that contains the correct row', ' IDoubleVector correct_row;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_row = row_val;', ' ', ' // We set the row, then the entry here', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the row, then that will ', ' // change the value contained in the row. We change the correct_row to reflect such.', ' if (j_entry == j_row) {', ' correct_row.setItem(i_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.'] | [' testGetRow(myMatrix, j_row, row_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);'] | [' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Here, we test first setting an entry in the matrix, then setting a column within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param entry_val The value that we will setValue with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetEntryColCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' ', ' // Note though that since we change the column later, if the column that we change contains the index of the', ' // entry value that we will set, then the correct value will be changed to what is contained in the column. ', ' // We account for that here by changing the correct value if that happens.', ' if (i_entry == i_col) {', ' correct_val = col_val.getItem(j_entry);', ' }', ' ', ' // The correct column is the column passed in since the column will never change.', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail(e.getMessage());', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting an entry within the matrix. ', ' * We check that the column is correct as well as the entry we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_entry The column for which we set the entry', ' * @param j_entry The row for which we set the entry', ' * @param i_col The index of the row that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val The column that we will setColumn with', ' */', ' private void testSetColEntryCombo (IDoubleMatrix myMatrix, int i_entry, int j_entry, int i_col, double entry_val, IDoubleVector col_val) {', ' IDoubleVector correct_col;', ' // A double that keeps track of what the correct value is.', ' double correct_val;', ' try {', ' // Set the correct value to the entry value.', ' correct_val = entry_val;', ' correct_col = col_val;', ' ', ' // We set the entry and the column here.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setEntry(j_entry, i_entry, entry_val);', ' ', ' // Note though that if the entry we set resides on the column, then that will ', ' // change the value contained in the column. We change the correct_col to reflect such.', ' if (i_entry == i_col) {', ' correct_col.setItem(j_entry, entry_val);', ' }', ' ', ' // Now, we test that the values are indeed correct.', ' testGetColumn(myMatrix, i_col, col_val);', ' testGetEntry(myMatrix, i_entry, j_entry, correct_val);', ' } catch (OutOfBoundsException e) {', ' fail("setEntry setRow combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testRowColCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', " // The correct row is set to the passed in column and won't change since we change the row after we change the column.", ' correct_row = row_val;', ' // The correct column is set to the passed in column (will change since row and column will always overlap)', ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setColumn(i_col, col_val);', ' myMatrix.setRow(j_row, row_val);', ' ', " // We now change the corresponding item in the column that would've been changed.", ' correct_col.setItem(j_row, row_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' ', ' /**', ' * Tests first setting a column in the matrix, then setting a row within the matrix. ', ' * We check that the column is correct as well as the row we changed within the matrix.', ' * ', ' * @param myMatrix The matrix that is passed in', ' * @param i_col The index of the row that we will set', ' * @param j_row The index of the column that we will set', ' * @param row_val The row that we will setRow with', ' * @param col_val the column that we will setColumn with', ' */', ' private void testColRowCombo (IDoubleMatrix myMatrix, int i_col, int j_row, IDoubleVector row_val, IDoubleVector col_val) {', ' // IDoubleVectors that hold the correct column and the correct row', ' IDoubleVector correct_col;', ' IDoubleVector correct_row;', ' ', ' try {', ' // The correct row is set to the passed in column initially (will change since row and column will always overlap)', ' correct_row = row_val;', " // The correct column is set to the passed in column and won't change since we change the column after we change the row.", ' correct_col = col_val;', ' ', ' // Now, we set the column and the row to the column/row passed in to the desired indices.', ' myMatrix.setRow(j_row, row_val);', ' myMatrix.setColumn(i_col, col_val);', ' ', " // We now change the corresponding item in the row that would've been changed.", ' correct_row.setItem(i_col, col_val.getItem(0));', ' ', ' // We verify here that the column and row match what should be the correct column and row.', ' testGetColumn(myMatrix, i_col, correct_col);', ' testGetRow(myMatrix, j_row, correct_row);', ' } catch (OutOfBoundsException e) {', ' fail("setRow setCol combo Failed: Encountered Out of Bounds Exception");', ' }', ' }', ' ', ' /**', ' * Tests that getRow works. We do so by comparing the row retrieved by getRow with', ' * an IDoubleVector that represents the row we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param j Index of row that we want to retrieve', " * @param expectedRow Expected row that we compare with our retrieved j'th row.", ' */', ' private void testGetRow (IDoubleMatrix myMatrix, int j, IDoubleVector expectedRow) {', ' IDoubleVector retrievedRow;', ' ', ' try {', ' // Retrieve the row from myMatrix', ' retrievedRow = myMatrix.getRow(j);', ' // In order to test that the retrieved row is correct, we iterate through every element in the retrieved row and compare it', ' // with the expected row', ' for (int i = 0; i < myMatrix.getNumColumns(); i++) {', ' assertTrue("getRow() Failed: Retrieved row did not match expected row", retrievedRow.getItem(i) == expectedRow.getItem(i));', ' }', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getRow() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getEntry works. We do so by utilizing getEntry, then verifying that', ' * the entry retrieved matches what we expected.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Column that we retrieve from', ' * @param j Row that we retrieve from', " * @param expectedVal Expected value that we expect to get from the i, j'th entry.", ' */', ' private void testGetEntry (IDoubleMatrix myMatrix, int i, int j, double expectedVal) {', ' // Attempt to retrieve entry. If it does not match, we print an appropriate error. If we encounter an OutOfBoundsException, we print a different error.', ' try {', ' assertTrue("getEntry() Failed: Retrieved value did not match expected value", myMatrix.getEntry(j, i) == expectedVal);', ' } catch (OutOfBoundsException e) {', ' fail("getEntry() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' /**', ' * Tests that getColumn works. We do so by comparing the column retrieved by getColumn with', ' * an IDoubleVector that represents the column we expect to get.', ' * ', ' * @param myMatrix Matrix that is tested', ' * @param i Index of column that we want to retrieve', " * @param expectedCol Expected column that we compare with our retrieved i'th column.", ' */', ' private void testGetColumn (IDoubleMatrix myMatrix, int i, IDoubleVector expectedCol) {', ' IDoubleVector retrievedColumn;', ' try {', ' // Retrieve the column from myMatrix', ' retrievedColumn = myMatrix.getColumn(i);', ' // In order to test that the retrieved column is correct, we iterate through every element in the retrieved column and compare it', ' // with the expected column', ' for (int j = 0; j < myMatrix.getNumRows(); j++) { ', ' assertTrue("getColumn() Failed: Retrieved column did not match expected column", retrievedColumn.getItem(j) == expectedCol.getItem(j));', ' } ', ' } catch (OutOfBoundsException e) {', ' // We fail instantly if we ever encounter an OutOfBoundsException', ' fail("getColumn() Failed: Encountered OutOfBoundsException");', ' }', ' }', ' ', ' // create and return a new random vector of the specified length', ' private IDoubleVector createRandomVector (int len, Random useMe) {', ' IDoubleVector returnVal = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' try {', ' returnVal.setItem (i, useMe.nextDouble ());', ' } catch (Exception e) {', ' throw new RuntimeException ("bad test case"); ', ' }', ' }', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyRows (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the rows', ' for (int i = 0; i < fillMe.getNumRows (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumColumns (), useMe);', ' fillMe.setRow (i, temp);', ' for (int j = 0; j < fillMe.getNumColumns (); j++) {', ' returnVal[i][j] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyColumns (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' // fills a double matrix, leaveing some rows empty... returns an array with all of the vals', ' private double [][] fillMatrixLeaveEmptyCols (IDoubleMatrix fillMe, Random useMe) {', ' ', ' double [][] returnVal = new double[fillMe.getNumRows ()][fillMe.getNumColumns ()];', ' ', ' // fill up all of the columns', ' for (int i = 0; i < fillMe.getNumColumns (); i++) {', ' ', ' // skip every other one', ' try {', ' if (useMe.nextInt (2) == 1) {', ' IDoubleVector temp = createRandomVector (fillMe.getNumRows (), useMe);', ' fillMe.setColumn (i, temp);', ' for (int j = 0; j < fillMe.getNumRows (); j++) {', ' returnVal[j][i] = temp.getItem (j); ', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' ', ' }', ' ', ' return returnVal;', ' }', ' ', ' private void makeSureAdditionResultIsCorrect (IDoubleMatrix first, IDoubleMatrix second,', ' double [][] firstArray, double [][] secondArray) {', ' ', ' // go through and make sure that second has the sum, and that first and firstArray are the same', ' try {', ' for (int i = 0; i < first.getNumRows (); i++) {', ' for (int j = 0; j < second.getNumColumns (); j++) {', ' assertTrue (firstArray[i][j] + secondArray[i][j] == second.getEntry (i, j));', ' assertTrue (firstArray[i][j] == first.getEntry (i, j));', ' }', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the matrix.");', ' }', ' }', ' ', ' private void makeSureSumColumnsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numRows; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numColumns; j++) {', ' total += firstArray[i][j];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' ', ' private void makeSureSumRowsIsCorrect (IDoubleVector res, int numRows, int numColumns, double [][] firstArray) {', ' ', ' // go through and make sure that each row is right', ' try {', ' for (int i = 0; i < numColumns; i++) {', ' double total = 0.0;', ' for (int j = 0; j < numRows; j++) {', ' total += firstArray[j][i];', ' }', ' assertTrue (total == res.getItem (i));', ' }', ' } catch (Exception e) {', ' fail ("Died when trying to check the res.");', ' }', ' }', ' ', ' public void testAddRowMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddColumnMajorToRowMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new RowMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyColumns (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyRows (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testAddRowMajorToColumnMajor () {', ' try {', ' // create two different row major matrices', ' Random myRand = new Random (122);', ' IDoubleMatrix first = new RowMajorDoubleMatrix (200, 100, 0.0);', ' IDoubleMatrix second = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] firstArray = fillMatrixLeaveEmptyRows (first, myRand);', ' double [][] secondArray = fillMatrixLeaveEmptyColumns (second, myRand);', ' ', ' // add them together', ' first.addMyselfToHim (second);', ' ', ' // and make sue we got the right answer', ' makeSureAdditionResultIsCorrect (first, second, firstArray, secondArray);', ' } catch (Exception e) {', ' fail ("Died when trying to fill the matrix.");', ' }', ' }', ' ', ' public void testSumColumnsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 200, 200, array);', ' }', ' ', ' public void testSumColumnsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (150, 150, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumColumns ();', ' makeSureSumColumnsIsCorrect (res, 150, 150, array);', ' }', ' ', ' public void testSumRowsInColumnMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new ColumnMajorDoubleMatrix (200, 100, 0.0);', ' double [][] array = fillMatrixLeaveEmptyColumns (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 200, 100, array);', ' }', ' ', ' public void testSumRowsInRowMatrix () {', ' Random myRand = new Random (122);', ' IDoubleMatrix tester = new RowMajorDoubleMatrix (100, 200, 0.0);', ' double [][] array = fillMatrixLeaveEmptyRows (tester, myRand);', ' IDoubleVector res = tester.sumRows ();', ' makeSureSumRowsIsCorrect (res, 100, 200, array);', ' }', ' ', ' ', ' ', '}', ''] | [] | Function 'testGetRow' used at line 1437 is defined at line 1604 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1437 is defined at line 1416 and has a Medium-Range dependency.
Variable 'j_row' used at line 1437 is defined at line 1416 and has a Medium-Range dependency.
Variable 'row_val' used at line 1437 is defined at line 1416 and has a Medium-Range dependency.
Function 'testGetEntry' used at line 1438 is defined at line 1630 and has a Long-Range dependency.
Variable 'myMatrix' used at line 1438 is defined at line 1416 and has a Medium-Range dependency.
Variable 'i_entry' used at line 1438 is defined at line 1416 and has a Medium-Range dependency.
Variable 'j_entry' used at line 1438 is defined at line 1416 and has a Medium-Range dependency.
Variable 'correct_val' used at line 1438 is defined at line 1423 and has a Medium-Range dependency. | {} | {'Function Long-Range': 2, 'Variable Medium-Range': 7} |
completion_java | MTreeTester | 211 | 211 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance'] | [' if (myList.size () == maxCount && distance < large) {'] | [' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 211}] | Global_Variable 'myList' used at line 211 is defined at line 186 and has a Medium-Range dependency.
Global_Variable 'maxCount' used at line 211 is defined at line 192 and has a Medium-Range dependency.
Variable 'distance' used at line 211 is defined at line 208 and has a Short-Range dependency.
Global_Variable 'large' used at line 211 is defined at line 189 and has a Medium-Range dependency. | {'If Condition': 1} | {'Global_Variable Medium-Range': 3, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 211 | 223 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance'] | [' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }'] | [' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 211}, {'reason_category': 'If Body', 'usage_line': 212}, {'reason_category': 'If Body', 'usage_line': 213}, {'reason_category': 'If Body', 'usage_line': 214}, {'reason_category': 'If Body', 'usage_line': 215}, {'reason_category': 'Define Stop Criteria', 'usage_line': 215}, {'reason_category': 'If Condition', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 216}, {'reason_category': 'Loop Body', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 217}, {'reason_category': 'Loop Body', 'usage_line': 217}, {'reason_category': 'If Body', 'usage_line': 218}, {'reason_category': 'Loop Body', 'usage_line': 218}, {'reason_category': 'If Body', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 219}, {'reason_category': 'If Body', 'usage_line': 220}, {'reason_category': 'If Body', 'usage_line': 220}, {'reason_category': 'If Body', 'usage_line': 221}, {'reason_category': 'If Body', 'usage_line': 222}, {'reason_category': 'If Body', 'usage_line': 223}] | Global_Variable 'myList' used at line 211 is defined at line 186 and has a Medium-Range dependency.
Global_Variable 'maxCount' used at line 211 is defined at line 192 and has a Medium-Range dependency.
Variable 'distance' used at line 211 is defined at line 208 and has a Short-Range dependency.
Global_Variable 'large' used at line 211 is defined at line 189 and has a Medium-Range dependency.
Variable 'i' used at line 215 is defined at line 215 and has a Short-Range dependency.
Global_Variable 'myList' used at line 215 is defined at line 186 and has a Medium-Range dependency.
Global_Variable 'myList' used at line 216 is defined at line 186 and has a Medium-Range dependency.
Variable 'i' used at line 216 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 216 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 216 is defined at line 214 and has a Short-Range dependency.
Global_Variable 'myList' used at line 217 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 217 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 217 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 217 is defined at line 214 and has a Short-Range dependency.
Variable 'i' used at line 218 is defined at line 215 and has a Short-Range dependency.
Variable 'badIndex' used at line 218 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'myList' used at line 222 is defined at line 186 and has a Long-Range dependency.
Variable 'badIndex' used at line 222 is defined at line 213 and has a Short-Range dependency. | {'If Condition': 2, 'If Body': 13, 'Define Stop Criteria': 1, 'Loop Body': 4} | {'Global_Variable Medium-Range': 5, 'Variable Short-Range': 11, 'Global_Variable Long-Range': 2} |
completion_java | MTreeTester | 216 | 216 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {'] | [' if (myList.get (i).distance > maxDist) {'] | [' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 216}, {'reason_category': 'Loop Body', 'usage_line': 216}] | Global_Variable 'myList' used at line 216 is defined at line 186 and has a Medium-Range dependency.
Variable 'i' used at line 216 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 216 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 216 is defined at line 214 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 1, 'Loop Body': 1} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 3} |
completion_java | MTreeTester | 217 | 218 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {'] | [' maxDist = myList.get (i).distance;', ' badIndex = i;'] | [' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 217}, {'reason_category': 'Loop Body', 'usage_line': 217}, {'reason_category': 'If Body', 'usage_line': 218}, {'reason_category': 'Loop Body', 'usage_line': 218}] | Global_Variable 'myList' used at line 217 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 217 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 217 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 217 is defined at line 214 and has a Short-Range dependency.
Variable 'i' used at line 218 is defined at line 215 and has a Short-Range dependency.
Variable 'badIndex' used at line 218 is defined at line 213 and has a Short-Range dependency. | {'If Body': 2, 'Loop Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 5} |
completion_java | MTreeTester | 222 | 222 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' '] | [' myList.remove (badIndex);'] | [' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 222}] | Global_Variable 'myList' used at line 222 is defined at line 186 and has a Long-Range dependency.
Variable 'badIndex' used at line 222 is defined at line 213 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 226 | 226 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room'] | [' if (myList.size () < maxCount) {'] | [' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 226}] | Global_Variable 'myList' used at line 226 is defined at line 186 and has a Long-Range dependency.
Global_Variable 'maxCount' used at line 226 is defined at line 192 and has a Long-Range dependency. | {'If Condition': 1} | {'Global_Variable Long-Range': 2} |
completion_java | MTreeTester | 231 | 232 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);'] | [' newOne.distance = distance;', ' myList.add (newOne); '] | [' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 231}, {'reason_category': 'If Body', 'usage_line': 232}] | Variable 'distance' used at line 231 is defined at line 208 and has a Medium-Range dependency.
Variable 'newOne' used at line 231 is defined at line 229 and has a Short-Range dependency.
Global_Variable 'myList' used at line 232 is defined at line 186 and has a Long-Range dependency.
Variable 'newOne' used at line 232 is defined at line 229 and has a Short-Range dependency. | {'If Body': 2} | {'Variable Medium-Range': 1, 'Variable Short-Range': 2, 'Global_Variable Long-Range': 1} |
completion_java | MTreeTester | 236 | 243 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance'] | [' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }'] | [' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 236}, {'reason_category': 'If Body', 'usage_line': 237}, {'reason_category': 'If Body', 'usage_line': 238}, {'reason_category': 'Define Stop Criteria', 'usage_line': 238}, {'reason_category': 'If Body', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 239}, {'reason_category': 'If Condition', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 240}, {'reason_category': 'If Body', 'usage_line': 240}, {'reason_category': 'Loop Body', 'usage_line': 241}, {'reason_category': 'If Body', 'usage_line': 241}, {'reason_category': 'Loop Body', 'usage_line': 242}, {'reason_category': 'If Body', 'usage_line': 242}, {'reason_category': 'If Body', 'usage_line': 243}] | Global_Variable 'myList' used at line 236 is defined at line 186 and has a Long-Range dependency.
Global_Variable 'maxCount' used at line 236 is defined at line 192 and has a Long-Range dependency.
Global_Variable 'large' used at line 237 is defined at line 189 and has a Long-Range dependency.
Variable 'i' used at line 238 is defined at line 238 and has a Short-Range dependency.
Global_Variable 'myList' used at line 238 is defined at line 186 and has a Long-Range dependency.
Global_Variable 'myList' used at line 239 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 239 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 239 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 239 is defined at line 237 and has a Short-Range dependency.
Global_Variable 'myList' used at line 240 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 240 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 240 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 240 is defined at line 237 and has a Short-Range dependency. | {'If Condition': 2, 'If Body': 7, 'Define Stop Criteria': 1, 'Loop Body': 4} | {'Global_Variable Long-Range': 6, 'Variable Short-Range': 3, 'Variable Long-Range': 2, 'Global_Variable Short-Range': 2} |
completion_java | MTreeTester | 239 | 241 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {'] | [' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }'] | [' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 239}, {'reason_category': 'If Condition', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 240}, {'reason_category': 'If Body', 'usage_line': 240}, {'reason_category': 'Loop Body', 'usage_line': 241}, {'reason_category': 'If Body', 'usage_line': 241}] | Global_Variable 'myList' used at line 239 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 239 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 239 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 239 is defined at line 237 and has a Short-Range dependency.
Global_Variable 'myList' used at line 240 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 240 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 240 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 240 is defined at line 237 and has a Short-Range dependency. | {'If Body': 3, 'Loop Body': 3, 'If Condition': 1} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 2, 'Variable Long-Range': 2, 'Global_Variable Short-Range': 2} |
completion_java | MTreeTester | 252 | 252 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {'] | [' returnVal.add (myList.get (i).myData); '] | [' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 252}] | Variable 'returnVal' used at line 252 is defined at line 250 and has a Short-Range dependency.
Global_Variable 'myList' used at line 252 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 252 is defined at line 251 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 1} |
completion_java | MTreeTester | 279 | 280 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);'] | [' if (dist > radius)', ' radius = dist;'] | [' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 279}, {'reason_category': 'If Body', 'usage_line': 280}] | Variable 'dist' used at line 279 is defined at line 278 and has a Short-Range dependency.
Global_Variable 'radius' used at line 279 is defined at line 266 and has a Medium-Range dependency.
Variable 'dist' used at line 280 is defined at line 278 and has a Short-Range dependency.
Global_Variable 'radius' used at line 280 is defined at line 266 and has a Medium-Range dependency. | {'If Condition': 1, 'If Body': 1} | {'Variable Short-Range': 2, 'Global_Variable Medium-Range': 2} |
completion_java | MTreeTester | 285 | 285 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {'] | [' return (me.center.getDistance (center) <= me.radius + radius);'] | [' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'center' used at line 285 is defined at line 265 and has a Medium-Range dependency.
Variable 'me' used at line 285 is defined at line 284 and has a Short-Range dependency.
Global_Variable 'radius' used at line 285 is defined at line 266 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 2, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 290 | 290 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {'] | [' return (checkMe.getDistance (center) <= radius);'] | [' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'checkMe' used at line 290 is defined at line 289 and has a Short-Range dependency.
Global_Variable 'center' used at line 290 is defined at line 265 and has a Medium-Range dependency.
Global_Variable 'radius' used at line 290 is defined at line 266 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 2} |
completion_java | MTreeTester | 298 | 298 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {'] | [' return radius + checkMe.getDistance (center); '] | [' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'radius' used at line 298 is defined at line 266 and has a Long-Range dependency.
Variable 'checkMe' used at line 298 is defined at line 297 and has a Short-Range dependency.
Global_Variable 'center' used at line 298 is defined at line 265 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 316 | 319 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {'] | [' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;'] | [' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 316}, {'reason_category': 'If Body', 'usage_line': 317}, {'reason_category': 'Else Reasoning', 'usage_line': 318}, {'reason_category': 'Else Reasoning', 'usage_line': 319}] | Global_Variable 'value' used at line 316 is defined at line 307 and has a Short-Range dependency.
Variable 'toMe' used at line 316 is defined at line 315 and has a Short-Range dependency.
Global_Variable 'value' used at line 317 is defined at line 307 and has a Short-Range dependency.
Variable 'toMe' used at line 317 is defined at line 315 and has a Short-Range dependency.
Variable 'toMe' used at line 319 is defined at line 315 and has a Short-Range dependency.
Global_Variable 'value' used at line 319 is defined at line 307 and has a Medium-Range dependency. | {'If Condition': 1, 'If Body': 1, 'Else Reasoning': 2} | {'Global_Variable Short-Range': 2, 'Variable Short-Range': 3, 'Global_Variable Medium-Range': 1} |
completion_java | MTreeTester | 338 | 342 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {'] | [' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }'] | [' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 338}, {'reason_category': 'Loop Body', 'usage_line': 339}, {'reason_category': 'Loop Body', 'usage_line': 340}, {'reason_category': 'Loop Body', 'usage_line': 341}, {'reason_category': 'Loop Body', 'usage_line': 342}] | Variable 'i' used at line 338 is defined at line 338 and has a Short-Range dependency.
Global_Variable 'me' used at line 338 is defined at line 327 and has a Medium-Range dependency.
Global_Variable 'me' used at line 339 is defined at line 327 and has a Medium-Range dependency.
Variable 'i' used at line 339 is defined at line 338 and has a Short-Range dependency.
Variable 'diff' used at line 340 is defined at line 339 and has a Short-Range dependency.
Variable 'diff' used at line 341 is defined at line 340 and has a Short-Range dependency.
Variable 'distance' used at line 341 is defined at line 336 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 4} | {'Variable Short-Range': 5, 'Global_Variable Medium-Range': 2} |
completion_java | MTreeTester | 346 | 346 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }'] | [' return Math.sqrt(distance);'] | [' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'distance' used at line 346 is defined at line 336 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1} |
completion_java | MTreeTester | 378 | 382 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node'] | [' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }'] | [' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 378}, {'reason_category': 'If Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 380}, {'reason_category': 'If Body', 'usage_line': 381}, {'reason_category': 'If Body', 'usage_line': 382}] | Global_Variable 'myData' used at line 378 is defined at line 355 and has a Medium-Range dependency.
Function 'getMaxSize' used at line 378 is defined at line 423 and has a Long-Range dependency.
Class 'PointABCD' used at line 379 is defined at line 157 and has a Long-Range dependency.
Global_Variable 'myData' used at line 379 is defined at line 355 and has a Medium-Range dependency.
Class 'LeafMTreeNodeABCD' used at line 380 is defined at line 351 and has a Medium-Range dependency.
Variable 'newOne' used at line 380 is defined at line 379 and has a Short-Range dependency.
Variable 'returnVal' used at line 381 is defined at line 380 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 4} | {'Global_Variable Medium-Range': 2, 'Function Long-Range': 1, 'Class Long-Range': 1, 'Class Medium-Range': 1, 'Variable Short-Range': 2} |