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
⌀ |
---|---|---|---|---|---|---|---|---|---|---|
infilling_java | SparseArrayTester | 142 | 142 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want'] | [' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);'] | [' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 142}] | Global_Variable 'lastSlotReturned' used at line 142 is defined at line 83 and has a Long-Range dependency.
Global_Variable 'indices' used at line 142 is defined at line 79 and has a Long-Range dependency.
Variable 'position' used at line 142 is defined at line 139 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 145 | 145 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want'] | [' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);'] | [' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 145}] | Global_Variable 'lastSlotReturned' used at line 145 is defined at line 83 and has a Long-Range dependency.
Global_Variable 'numElements' used at line 145 is defined at line 81 and has a Long-Range dependency.
Global_Variable 'indices' used at line 145 is defined at line 79 and has a Long-Range dependency.
Variable 'position' used at line 145 is defined at line 139 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 149 | 149 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)'] | [' return null;'] | [' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 149}] | null | {'If Body': 1} | null |
infilling_java | SparseArrayTester | 153 | 153 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)'] | [' return null;'] | [' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 153}] | null | {'If Body': 1} | null |
infilling_java | SparseArrayTester | 152 | 153 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it"] | [' if (indices[lastSlotReturned] != position)', ' return null;'] | [' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 153}] | Global_Variable 'indices' used at line 152 is defined at line 79 and has a Long-Range dependency.
Global_Variable 'lastSlotReturned' used at line 152 is defined at line 83 and has a Long-Range dependency.
Variable 'position' used at line 152 is defined at line 139 and has a Medium-Range dependency. | {'If Condition': 1, 'If Body': 1} | {'Global_Variable Long-Range': 2, 'Variable Medium-Range': 1} |
infilling_java | SparseArrayTester | 164 | 165 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {'] | [' array = new TreeMap<Integer, T>();', ' }'] | ['', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 164 is defined at line 161 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 168 | 169 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {'] | [' array.put(position, element);', ' }'] | ['', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 168 is defined at line 161 and has a Short-Range dependency.
Variable 'position' used at line 168 is defined at line 167 and has a Short-Range dependency.
Variable 'element' used at line 168 is defined at line 167 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 2} |
infilling_java | SparseArrayTester | 172 | 173 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {'] | [' return array.get(position);', ' }'] | ['', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 172 is defined at line 161 and has a Medium-Range dependency.
Variable 'position' used at line 172 is defined at line 171 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 176 | 177 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {'] | [' return new IndexedIterator<T> (array);', ' }'] | ['}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 176 is defined at line 161 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | DoubleMatrixTester | 258 | 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': 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}, {'reason_category': 'Loop Body', 'usage_line': 262}] | 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': 5, 'If Condition': 1, 'If Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 6} |
infilling_java | DoubleMatrixTester | 260 | 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': '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}] | 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': 2, 'Loop Body': 2} | {'Variable Short-Range': 4} |
infilling_java | DoubleMatrixTester | 277 | 283 | ['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}, {'reason_category': 'Loop Body', 'usage_line': 278}, {'reason_category': 'If Condition', 'usage_line': 278}, {'reason_category': 'Loop Body', 'usage_line': 279}, {'reason_category': 'If Body', 'usage_line': 279}, {'reason_category': 'If Body', 'usage_line': 280}, {'reason_category': 'Loop Body', 'usage_line': 280}, {'reason_category': 'If Body', 'usage_line': 281}, {'reason_category': 'Loop Body', 'usage_line': 281}, {'reason_category': 'Loop Body', 'usage_line': 282}, {'reason_category': 'Loop Body', 'usage_line': 283}] | 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.
Variable 'myRow' used at line 278 is defined at line 277 and has a Short-Range dependency.
Global_Variable 'numCols' used at line 279 is defined at line 227 and has a Long-Range dependency.
Global_Variable 'backValue' used at line 279 is defined at line 229 and has a Long-Range dependency.
Variable 'myRow' used at line 279 is defined at line 277 and has a Short-Range dependency.
Global_Variable 'myData' used at line 280 is defined at line 226 and has a Long-Range dependency.
Variable 'row' used at line 280 is defined at line 276 and has a Short-Range dependency.
Variable 'myRow' used at line 280 is defined at line 279 and has a Short-Range dependency.
Variable 'myRow' used at line 282 is defined at line 279 and has a Short-Range dependency.
Variable 'i' used at line 282 is defined at line 272 and has a Short-Range dependency.
Variable 'setToMe' used at line 282 is defined at line 272 and has a Short-Range dependency.
Variable 'row' used at line 282 is defined at line 276 and has a Short-Range dependency. | {'Loop Body': 7, 'If Condition': 1, 'If Body': 3} | {'Global_Variable Long-Range': 4, 'Variable Short-Range': 9} |
infilling_java | DoubleMatrixTester | 279 | 281 | ['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': 279}, {'reason_category': 'If Body', 'usage_line': 279}, {'reason_category': 'If Body', 'usage_line': 280}, {'reason_category': 'Loop Body', 'usage_line': 280}, {'reason_category': 'If Body', 'usage_line': 281}, {'reason_category': 'Loop Body', 'usage_line': 281}] | Global_Variable 'numCols' used at line 279 is defined at line 227 and has a Long-Range dependency.
Global_Variable 'backValue' used at line 279 is defined at line 229 and has a Long-Range dependency.
Variable 'myRow' used at line 279 is defined at line 277 and has a Short-Range dependency.
Global_Variable 'myData' used at line 280 is defined at line 226 and has a Long-Range dependency.
Variable 'row' used at line 280 is defined at line 276 and has a Short-Range dependency.
Variable 'myRow' used at line 280 is defined at line 279 and has a Short-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 3} |
infilling_java | DoubleMatrixTester | 293 | 294 | ['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': 293}, {'reason_category': 'If Body', 'usage_line': 294}] | Global_Variable 'backValue' used at line 293 is defined at line 229 and has a Long-Range dependency. | {'If Body': 2} | {'Global_Variable Long-Range': 1} |
infilling_java | DoubleMatrixTester | 292 | 296 | ['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': 292}, {'reason_category': 'If Body', 'usage_line': 293}, {'reason_category': 'If Body', 'usage_line': 294}] | Variable 'myRow' used at line 292 is defined at line 291 and has a Short-Range dependency.
Global_Variable 'backValue' used at line 293 is defined at line 229 and has a Long-Range dependency.
Variable 'myRow' used at line 295 is defined at line 291 and has a Short-Range dependency.
Variable 'i' used at line 295 is defined at line 286 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleMatrixTester | 327 | 329 | ['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}, {'reason_category': 'If Body', 'usage_line': 329}] | 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': 3} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 3} |
infilling_java | DoubleMatrixTester | 326 | 331 | ['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': 326}, {'reason_category': 'If Body', 'usage_line': 327}, {'reason_category': 'If Body', 'usage_line': 328}, {'reason_category': 'If Body', 'usage_line': 329}] | Variable 'myRow' used at line 326 is defined at line 325 and has a Short-Range dependency.
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.
Variable 'myRow' used at line 330 is defined at line 327 and has a Short-Range dependency.
Variable 'i' used at line 330 is defined at line 320 and has a Short-Range dependency.
Variable 'setToMe' used at line 330 is defined at line 320 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 3} | {'Variable Short-Range': 7, 'Global_Variable Long-Range': 3} |
infilling_java | DoubleMatrixTester | 334 | 335 | ['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);', ' }', ' ', ' ', ' ', '}', ''] | [] | Global_Variable 'numRows' used at line 334 is defined at line 228 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | DoubleMatrixTester | 338 | 339 | ['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);', ' }', ' ', ' ', ' ', '}', ''] | [] | Global_Variable 'numCols' used at line 338 is defined at line 227 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | DoubleMatrixTester | 358 | 359 | ['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} |
infilling_java | DoubleMatrixTester | 362 | 363 | ['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} |
infilling_java | DoubleMatrixTester | 366 | 367 | ['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} |
infilling_java | DoubleMatrixTester | 370 | 371 | ['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} |
infilling_java | DoubleMatrixTester | 376 | 380 | ['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}, {'reason_category': 'Loop Body', 'usage_line': 380}] | 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': 5} | {'Function Medium-Range': 1, 'Variable Short-Range': 8} |
infilling_java | DoubleMatrixTester | 375 | 381 | ['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': 375}, {'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}, {'reason_category': 'Loop Body', 'usage_line': 380}] | Variable 'i' used at line 375 is defined at line 375 and has a Short-Range dependency.
Variable 'numCols' used at line 375 is defined at line 374 and has a Short-Range dependency.
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. | {'Define Stop Criteria': 1, 'Loop Body': 5} | {'Variable Short-Range': 10, 'Function Medium-Range': 1} |
infilling_java | DoubleMatrixTester | 384 | 385 | ['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} |
infilling_java | DoubleMatrixTester | 388 | 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);', ' }', ' ', ' ', ' ', '}', ''] | [] | 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} |
infilling_java | DoubleMatrixTester | 392 | 393 | ['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} |
infilling_java | DoubleMatrixTester | 396 | 397 | ['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} |
infilling_java | DoubleMatrixTester | 400 | 401 | ['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} |
infilling_java | DoubleMatrixTester | 408 | 409 | ['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} |
infilling_java | DoubleMatrixTester | 412 | 413 | ['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} |
infilling_java | DoubleMatrixTester | 416 | 417 | ['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} |
infilling_java | DoubleMatrixTester | 420 | 421 | ['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} |
infilling_java | DoubleMatrixTester | 426 | 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': '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}] | 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. | {'Loop Body': 5} | {'Function Medium-Range': 1, 'Variable Short-Range': 8} |
infilling_java | DoubleMatrixTester | 425 | 431 | ['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} |
infilling_java | DoubleMatrixTester | 434 | 435 | ['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} |
infilling_java | DoubleMatrixTester | 438 | 439 | ['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} |
infilling_java | DoubleMatrixTester | 442 | 443 | ['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} |
infilling_java | DoubleMatrixTester | 446 | 447 | ['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} |
infilling_java | DoubleMatrixTester | 450 | 451 | ['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} |
infilling_java | DoubleMatrixTester | 747 | 748 | ['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 'simpleInitializeMatrix' used at line 747 is defined at line 746 and has a Short-Range dependency.
Variable 'matrix' used at line 747 is defined at line 746 and has a Short-Range dependency. | {} | {'Function Short-Range': 1, 'Variable Short-Range': 1} |
infilling_java | DoubleMatrixTester | 886 | 886 | ['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 Short-Range': 2} |
infilling_java | DoubleMatrixTester | 936 | 938 | ['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 936 is defined at line 922 and has a Medium-Range dependency.
Variable 'column' used at line 936 is defined at line 923 and has a Medium-Range dependency.
Function 'checkListsAreEqual' used at line 937 is defined at line 575 and has a Long-Range dependency.
Variable 'matrix' used at line 937 is defined at line 922 and has a Medium-Range dependency. | {} | {'Variable Medium-Range': 3, 'Function Long-Range': 1} |
infilling_java | DoubleMatrixTester | 982 | 987 | ['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 'simpleInitializeMatrix' used at line 982 is defined at line 746 and has a Long-Range dependency.
Variable 'cMatrix' used at line 982 is defined at line 979 and has a Short-Range dependency.
Function 'simpleInitializeMatrix' used at line 983 is defined at line 746 and has a Long-Range dependency.
Variable 'rMatrix' used at line 983 is defined at line 980 and has a Short-Range dependency.
Function 'seeIfSetRowWorks' used at line 985 is defined at line 997 and has a Medium-Range dependency.
Variable 'cMatrix' used at line 985 is defined at line 979 and has a Short-Range dependency.
Function 'seeIfSetRowWorks' used at line 986 is defined at line 997 and has a Medium-Range dependency.
Variable 'rMatrix' used at line 986 is defined at line 980 and has a Short-Range dependency. | {} | {'Function Long-Range': 2, 'Variable Short-Range': 4, 'Function Medium-Range': 2} |
infilling_java | DoubleMatrixTester | 1,056 | 1,058 | ['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 'seeIfComplexSetAndGetWorks' used at line 1056 is defined at line 1066 and has a Short-Range dependency.
Variable 'cMatrix' used at line 1056 is defined at line 1053 and has a Short-Range dependency.
Function 'seeIfComplexSetAndGetWorks' used at line 1057 is defined at line 1066 and has a Short-Range dependency.
Variable 'rMatrix' used at line 1057 is defined at line 1054 and has a Short-Range dependency. | {} | {'Function Short-Range': 2, 'Variable Short-Range': 2} |
infilling_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} |
infilling_java | DoubleMatrixTester | 1,232 | 1,242 | ['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': 1232}, {'reason_category': 'Loop Body', 'usage_line': 1233}, {'reason_category': 'Loop Body', 'usage_line': 1234}, {'reason_category': 'Loop Body', 'usage_line': 1235}, {'reason_category': 'Loop Body', 'usage_line': 1236}, {'reason_category': 'Loop Body', 'usage_line': 1237}, {'reason_category': 'Loop Body', 'usage_line': 1238}, {'reason_category': 'Loop Body', 'usage_line': 1239}, {'reason_category': 'Loop Body', 'usage_line': 1240}, {'reason_category': 'Loop Body', 'usage_line': 1241}, {'reason_category': 'Loop Body', 'usage_line': 1242}] | 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.
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': 11} | {'Class Long-Range': 2, 'Variable Long-Range': 6, 'Variable Short-Range': 8, 'Variable Medium-Range': 10, 'Function Long-Range': 2} |
infilling_java | DoubleMatrixTester | 1,275 | 1,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': 1275}, {'reason_category': 'Loop Body', 'usage_line': 1276}, {'reason_category': 'Loop Body', 'usage_line': 1277}, {'reason_category': 'Loop Body', 'usage_line': 1278}] | 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': 4} | {'Class Long-Range': 1, 'Variable Long-Range': 3, 'Variable Short-Range': 4, 'Variable Medium-Range': 5, 'Function Long-Range': 1} |
infilling_java | DoubleMatrixTester | 1,389 | 1,390 | ['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}, {'reason_category': 'If Body', 'usage_line': 1390}] | 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': 2} | {'Variable Medium-Range': 2, 'Variable Short-Range': 1} |
infilling_java | DoubleMatrixTester | 1,433 | 1,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);', ' }', ' ', ' ', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 1433}, {'reason_category': 'If Body', 'usage_line': 1434}] | 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': 2} | {'Variable Short-Range': 1, 'Variable Medium-Range': 2} |
infilling_java | DoubleMatrixTester | 1,738 | 1,743 | ['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': 1738}, {'reason_category': 'If Body', 'usage_line': 1738}, {'reason_category': 'Loop body', 'usage_line': 1738}, {'reason_category': 'Loop body', 'usage_line': 1739}, {'reason_category': 'If Body', 'usage_line': 1739}, {'reason_category': 'Loop body', 'usage_line': 1740}, {'reason_category': 'If Body', 'usage_line': 1740}, {'reason_category': 'Define Stop Criteria', 'usage_line': 1740}, {'reason_category': 'If Body', 'usage_line': 1741}, {'reason_category': 'Loop body', 'usage_line': 1741}, {'reason_category': 'Loop body', 'usage_line': 1742}, {'reason_category': 'If Body', 'usage_line': 1742}, {'reason_category': 'Loop body', 'usage_line': 1743}, {'reason_category': 'If Body', 'usage_line': 1743}] | Function 'createRandomVector' used at line 1738 is defined at line 1664 and has a Long-Range dependency.
Variable 'fillMe' used at line 1738 is defined at line 1728 and has a Short-Range dependency.
Variable 'useMe' used at line 1738 is defined at line 1728 and has a Short-Range dependency.
Variable 'fillMe' used at line 1739 is defined at line 1728 and has a Medium-Range dependency.
Variable 'i' used at line 1739 is defined at line 1733 and has a Short-Range dependency.
Variable 'temp' used at line 1739 is defined at line 1738 and has a Short-Range dependency.
Variable 'j' used at line 1740 is defined at line 1740 and has a Short-Range dependency.
Variable 'fillMe' used at line 1740 is defined at line 1728 and has a Medium-Range dependency.
Variable 'temp' used at line 1741 is defined at line 1738 and has a Short-Range dependency.
Variable 'j' used at line 1741 is defined at line 1740 and has a Short-Range dependency.
Variable 'returnVal' used at line 1741 is defined at line 1730 and has a Medium-Range dependency.
Variable 'i' used at line 1741 is defined at line 1733 and has a Short-Range dependency. | {'If Body': 6, 'Define Stop Criteria': 1} | {'Function Long-Range': 1, 'Variable Short-Range': 8, 'Variable Medium-Range': 3} |
infilling_java | DoubleMatrixTester | 1,760 | 1,762 | ['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': 1760}, {'reason_category': 'Loop body', 'usage_line': 1761}, {'reason_category': 'Loop body', 'usage_line': 1762}] | Variable 'firstArray' used at line 1760 is defined at line 1754 and has a Short-Range dependency.
Variable 'i' used at line 1760 is defined at line 1758 and has a Short-Range dependency.
Variable 'j' used at line 1760 is defined at line 1759 and has a Short-Range dependency.
Variable 'secondArray' used at line 1760 is defined at line 1754 and has a Short-Range dependency.
Variable 'second' used at line 1760 is defined at line 1753 and has a Short-Range dependency.
Variable 'firstArray' used at line 1761 is defined at line 1754 and has a Short-Range dependency.
Variable 'i' used at line 1761 is defined at line 1758 and has a Short-Range dependency.
Variable 'j' used at line 1761 is defined at line 1759 and has a Short-Range dependency.
Variable 'first' used at line 1761 is defined at line 1753 and has a Short-Range dependency. | {} | {'Variable Short-Range': 9} |
infilling_java | DoubleMatrixTester | 1,776 | 1,777 | ['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': 1776}, {'reason_category': 'Loop body', 'usage_line': 1777}] | Variable 'firstArray' used at line 1776 is defined at line 1769 and has a Short-Range dependency.
Variable 'i' used at line 1776 is defined at line 1773 and has a Short-Range dependency.
Variable 'j' used at line 1776 is defined at line 1775 and has a Short-Range dependency.
Variable 'total' used at line 1776 is defined at line 1774 and has a Short-Range dependency. | {} | {'Variable Short-Range': 4} |
infilling_java | DoubleMatrixTester | 1,774 | 1,779 | ['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': 1774}, {'reason_category': 'Define Stop Criteria', 'usage_line': 1775}, {'reason_category': 'Loop body', 'usage_line': 1775}, {'reason_category': 'Loop body', 'usage_line': 1776}, {'reason_category': 'Loop body', 'usage_line': 1777}, {'reason_category': 'Loop body', 'usage_line': 1778}, {'reason_category': 'Loop body', 'usage_line': 1779}] | Variable 'j' used at line 1775 is defined at line 1775 and has a Short-Range dependency.
Variable 'numColumns' used at line 1775 is defined at line 1769 and has a Short-Range dependency.
Variable 'firstArray' used at line 1776 is defined at line 1769 and has a Short-Range dependency.
Variable 'i' used at line 1776 is defined at line 1773 and has a Short-Range dependency.
Variable 'j' used at line 1776 is defined at line 1775 and has a Short-Range dependency.
Variable 'total' used at line 1776 is defined at line 1774 and has a Short-Range dependency.
Variable 'total' used at line 1778 is defined at line 1774 and has a Short-Range dependency.
Variable 'res' used at line 1778 is defined at line 1769 and has a Short-Range dependency.
Variable 'i' used at line 1778 is defined at line 1773 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Variable Short-Range': 9} |
infilling_java | DoubleMatrixTester | 1,793 | 1,794 | ['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': 1793}, {'reason_category': 'Loop body', 'usage_line': 1794}] | Variable 'firstArray' used at line 1793 is defined at line 1786 and has a Short-Range dependency.
Variable 'j' used at line 1793 is defined at line 1792 and has a Short-Range dependency.
Variable 'i' used at line 1793 is defined at line 1790 and has a Short-Range dependency.
Variable 'total' used at line 1793 is defined at line 1791 and has a Short-Range dependency. | {} | {'Variable Short-Range': 4} |
infilling_java | DoubleMatrixTester | 1,791 | 1,796 | ['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': 1791}, {'reason_category': 'Define Stop Criteria', 'usage_line': 1792}, {'reason_category': 'Loop body', 'usage_line': 1792}, {'reason_category': 'Loop body', 'usage_line': 1793}, {'reason_category': 'Loop body', 'usage_line': 1794}, {'reason_category': 'Loop body', 'usage_line': 1795}, {'reason_category': 'Loop body', 'usage_line': 1796}] | Variable 'j' used at line 1792 is defined at line 1792 and has a Short-Range dependency.
Variable 'numRows' used at line 1792 is defined at line 1786 and has a Short-Range dependency.
Variable 'firstArray' used at line 1793 is defined at line 1786 and has a Short-Range dependency.
Variable 'j' used at line 1793 is defined at line 1792 and has a Short-Range dependency.
Variable 'i' used at line 1793 is defined at line 1790 and has a Short-Range dependency.
Variable 'total' used at line 1793 is defined at line 1791 and has a Short-Range dependency.
Variable 'total' used at line 1795 is defined at line 1791 and has a Short-Range dependency.
Variable 'res' used at line 1795 is defined at line 1786 and has a Short-Range dependency.
Variable 'i' used at line 1795 is defined at line 1790 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Variable Short-Range': 9} |
infilling_java | DoubleVectorTester | 36 | 36 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)'] | [' returnVal = returnVal + ", ";'] | [' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 36}] | Variable 'returnVal' used at line 36 is defined at line 31 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 33 | 39 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {'] | [' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }'] | [' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 33}, {'reason_category': 'Loop Body', 'usage_line': 34}, {'reason_category': 'If Condition', 'usage_line': 35}, {'reason_category': 'Loop Body', 'usage_line': 35}, {'reason_category': 'If Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 37}, {'reason_category': 'Loop Body', 'usage_line': 38}] | Function 'getItem' used at line 33 is defined at line 18 and has a Medium-Range dependency.
Variable 'i' used at line 33 is defined at line 32 and has a Short-Range dependency.
Variable 'i' used at line 35 is defined at line 32 and has a Short-Range dependency.
Variable 'returnVal' used at line 36 is defined at line 31 and has a Short-Range dependency.
Variable 'returnVal' used at line 38 is defined at line 36 and has a Short-Range dependency.
Variable 'curItem' used at line 38 is defined at line 33 and has a Short-Range dependency. | {'Loop Body': 6, 'If Condition': 1, 'If Body': 1} | {'Function Medium-Range': 1, 'Variable Short-Range': 5} |
infilling_java | DoubleVectorTester | 51 | 52 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {'] | [' return Math.round (getItem (whichOne)); ', ' }'] | ['}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Library 'Math' used at line 51 is defined at line 3 and has a Long-Range dependency.
Function 'getItem' used at line 51 is defined at line 18 and has a Long-Range dependency.
Variable 'whichOne' used at line 51 is defined at line 50 and has a Short-Range dependency. | {} | {'Library Long-Range': 1, 'Function Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 185 | 190 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {'] | [' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}'] | ['', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'message' used at line 188 is defined at line 187 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 188 | 189 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {'] | [' super(message);', ' }'] | ['}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'message' used at line 188 is defined at line 187 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 220 | 221 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {'] | [' myData[i] = 0.0;', ' }'] | [' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 220}, {'reason_category': 'Loop Body', 'usage_line': 221}] | Global_Variable 'myData' used at line 220 is defined at line 216 and has a Short-Range dependency.
Variable 'i' used at line 220 is defined at line 219 and has a Short-Range dependency. | {'Loop Body': 2} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 219 | 225 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array'] | [' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }'] | [' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 220}, {'reason_category': 'Loop Body', 'usage_line': 221}] | Variable 'i' used at line 219 is defined at line 219 and has a Short-Range dependency.
Variable 'len' used at line 219 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'myData' used at line 220 is defined at line 216 and has a Short-Range dependency.
Variable 'i' used at line 220 is defined at line 219 and has a Short-Range dependency.
Variable 'initialValue' used at line 224 is defined at line 213 and has a Medium-Range dependency.
Global_Variable 'baselineData' used at line 224 is defined at line 204 and has a Medium-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 3, 'Global_Variable Short-Range': 1, 'Variable Medium-Range': 1, 'Global_Variable Medium-Range': 1} |
infilling_java | DoubleVectorTester | 228 | 229 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {'] | [' return myData.length;', ' }'] | [' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Global_Variable 'myData' used at line 228 is defined at line 200 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | DoubleVectorTester | 237 | 238 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {'] | [' returnVal += Math.abs (myData[i] + baselineData);', ' }'] | [' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 237}, {'reason_category': 'Loop Body', 'usage_line': 238}] | Library 'Math' used at line 237 is defined at line 3 and has a Long-Range dependency.
Global_Variable 'myData' used at line 237 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 237 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 237 is defined at line 204 and has a Long-Range dependency.
Variable 'returnVal' used at line 237 is defined at line 235 and has a Short-Range dependency. | {'Loop Body': 2} | {'Library Long-Range': 1, 'Global_Variable Long-Range': 2, 'Variable Short-Range': 2} |
infilling_java | DoubleVectorTester | 235 | 240 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {'] | [' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }'] | [' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 236}, {'reason_category': 'Loop Body', 'usage_line': 237}, {'reason_category': 'Loop Body', 'usage_line': 238}] | Variable 'i' used at line 236 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'myData' used at line 236 is defined at line 200 and has a Long-Range dependency.
Library 'Math' used at line 237 is defined at line 3 and has a Long-Range dependency.
Global_Variable 'myData' used at line 237 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 237 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 237 is defined at line 204 and has a Long-Range dependency.
Variable 'returnVal' used at line 237 is defined at line 235 and has a Short-Range dependency.
Variable 'returnVal' used at line 239 is defined at line 235 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 3, 'Library Long-Range': 1} |
infilling_java | DoubleVectorTester | 236 | 240 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;'] | [' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }'] | [' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 236}, {'reason_category': 'Loop Body', 'usage_line': 237}, {'reason_category': 'Loop Body', 'usage_line': 238}] | Variable 'i' used at line 236 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'myData' used at line 236 is defined at line 200 and has a Long-Range dependency.
Library 'Math' used at line 237 is defined at line 3 and has a Long-Range dependency.
Global_Variable 'myData' used at line 237 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 237 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 237 is defined at line 204 and has a Long-Range dependency.
Variable 'returnVal' used at line 237 is defined at line 235 and has a Short-Range dependency.
Variable 'returnVal' used at line 239 is defined at line 235 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 3, 'Library Long-Range': 1} |
infilling_java | DoubleVectorTester | 245 | 248 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {'] | [' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }'] | [' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 245}, {'reason_category': 'Loop Body', 'usage_line': 246}, {'reason_category': 'Loop Body', 'usage_line': 247}, {'reason_category': 'Loop Body', 'usage_line': 248}] | Global_Variable 'myData' used at line 245 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 245 is defined at line 244 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 246 is defined at line 204 and has a Long-Range dependency.
Variable 'trueVal' used at line 246 is defined at line 245 and has a Short-Range dependency.
Variable 'trueVal' used at line 247 is defined at line 246 and has a Short-Range dependency.
Variable 'total' used at line 247 is defined at line 243 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 247 is defined at line 204 and has a Long-Range dependency.
Global_Variable 'myData' used at line 247 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 247 is defined at line 244 and has a Short-Range dependency. | {'Loop Body': 4} | {'Global_Variable Long-Range': 4, 'Variable Short-Range': 5} |
infilling_java | DoubleVectorTester | 243 | 250 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {'] | [' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }'] | [' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 244}, {'reason_category': 'Loop Body', 'usage_line': 245}, {'reason_category': 'Loop Body', 'usage_line': 246}, {'reason_category': 'Loop Body', 'usage_line': 247}, {'reason_category': 'Loop Body', 'usage_line': 248}] | Function 'l1Norm' used at line 243 is defined at line 234 and has a Short-Range dependency.
Variable 'i' used at line 244 is defined at line 244 and has a Short-Range dependency.
Global_Variable 'myData' used at line 244 is defined at line 200 and has a Long-Range dependency.
Global_Variable 'myData' used at line 245 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 245 is defined at line 244 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 246 is defined at line 204 and has a Long-Range dependency.
Variable 'trueVal' used at line 246 is defined at line 245 and has a Short-Range dependency.
Variable 'trueVal' used at line 247 is defined at line 246 and has a Short-Range dependency.
Variable 'total' used at line 247 is defined at line 243 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 247 is defined at line 204 and has a Long-Range dependency.
Global_Variable 'myData' used at line 247 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 247 is defined at line 244 and has a Short-Range dependency.
Variable 'total' used at line 249 is defined at line 243 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 249 is defined at line 204 and has a Long-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 4} | {'Function Short-Range': 1, 'Variable Short-Range': 7, 'Global_Variable Long-Range': 6} |
infilling_java | DoubleVectorTester | 260 | 263 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {'] | [' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }'] | [' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 261}, {'reason_category': 'Loop Body', 'usage_line': 262}, {'reason_category': 'Loop Body', 'usage_line': 263}] | Variable 'addToThisOne' used at line 260 is defined at line 252 and has a Short-Range dependency.
Variable 'i' used at line 260 is defined at line 259 and has a Short-Range dependency.
Global_Variable 'myData' used at line 261 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 261 is defined at line 259 and has a Short-Range dependency.
Variable 'value' used at line 261 is defined at line 260 and has a Short-Range dependency.
Variable 'addToThisOne' used at line 262 is defined at line 252 and has a Short-Range dependency.
Variable 'i' used at line 262 is defined at line 259 and has a Short-Range dependency.
Variable 'value' used at line 262 is defined at line 261 and has a Short-Range dependency. | {'Loop Body': 4} | {'Variable Short-Range': 7, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 286 | 287 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {'] | [' baselineData += addMe;', ' }'] | [' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'addMe' used at line 286 is defined at line 285 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 286 is defined at line 204 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 327 | 332 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {'] | [' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }'] | [' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 327}, {'reason_category': 'Loop Body', 'usage_line': 328}, {'reason_category': 'Loop Body', 'usage_line': 329}, {'reason_category': 'Loop Body', 'usage_line': 330}, {'reason_category': 'Loop Body', 'usage_line': 331}, {'reason_category': 'Loop Body', 'usage_line': 332}] | Variable 'el' used at line 327 is defined at line 326 and has a Short-Range dependency.
Variable 'el' used at line 328 is defined at line 326 and has a Short-Range dependency.
Variable 'value' used at line 329 is defined at line 327 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 329 is defined at line 304 and has a Medium-Range dependency.
Variable 'total' used at line 329 is defined at line 325 and has a Short-Range dependency.
Variable 'newValue' used at line 330 is defined at line 329 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 330 is defined at line 304 and has a Medium-Range dependency.
Variable 'total' used at line 330 is defined at line 325 and has a Short-Range dependency.
Variable 'value' used at line 330 is defined at line 327 and has a Short-Range dependency.
Global_Variable 'nonEmptyEntries' used at line 331 is defined at line 300 and has a Long-Range dependency.
Variable 'position' used at line 331 is defined at line 328 and has a Short-Range dependency.
Variable 'value' used at line 331 is defined at line 330 and has a Short-Range dependency. | {'Loop Body': 6} | {'Variable Short-Range': 9, 'Global_Variable Medium-Range': 2, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 343 | 345 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {'] | [' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }'] | [' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 343}, {'reason_category': 'Loop Body', 'usage_line': 344}, {'reason_category': 'Loop Body', 'usage_line': 345}] | Library 'Math' used at line 343 is defined at line 3 and has a Long-Range dependency.
Variable 'el' used at line 343 is defined at line 342 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 343 is defined at line 304 and has a Long-Range dependency.
Variable 'returnVal' used at line 343 is defined at line 340 and has a Short-Range dependency.
Variable 'nonEmptyEls' used at line 344 is defined at line 341 and has a Short-Range dependency. | {'Loop Body': 3} | {'Library Long-Range': 1, 'Variable Short-Range': 3, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 360 | 364 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {'] | [' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }'] | [' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 360}, {'reason_category': 'Loop Body', 'usage_line': 361}, {'reason_category': 'Loop Body', 'usage_line': 362}, {'reason_category': 'Loop Body', 'usage_line': 363}, {'reason_category': 'Loop Body', 'usage_line': 364}] | Variable 'el' used at line 360 is defined at line 359 and has a Short-Range dependency.
Variable 'el' used at line 361 is defined at line 359 and has a Short-Range dependency.
Variable 'addToHim' used at line 362 is defined at line 352 and has a Short-Range dependency.
Variable 'curIndex' used at line 362 is defined at line 361 and has a Short-Range dependency.
Variable 'myVal' used at line 362 is defined at line 360 and has a Short-Range dependency.
Variable 'addToHim' used at line 363 is defined at line 352 and has a Medium-Range dependency.
Variable 'curIndex' used at line 363 is defined at line 361 and has a Short-Range dependency.
Variable 'myVal' used at line 363 is defined at line 362 and has a Short-Range dependency. | {'Loop Body': 5} | {'Variable Short-Range': 7, 'Variable Medium-Range': 1} |
infilling_java | DoubleVectorTester | 371 | 372 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {'] | [' baselineValue += addMe;', ' }'] | [' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'addMe' used at line 371 is defined at line 370 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 371 is defined at line 304 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 384 | 384 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {'] | [' return baselineValue;'] | [' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 384}] | Global_Variable 'baselineValue' used at line 384 is defined at line 304 and has a Long-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 386 | 387 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {'] | [' return myVal + baselineValue;', ' }'] | [' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 386}, {'reason_category': 'Else Reasoning', 'usage_line': 387}] | Variable 'myVal' used at line 386 is defined at line 382 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 386 is defined at line 304 and has a Long-Range dependency. | {'Else Reasoning': 2} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 402 | 403 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {'] | [' return myLength;', ' }'] | ['}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Global_Variable 'myLength' used at line 402 is defined at line 307 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 427 | 427 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && '] | [' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))'] | [' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 427}] | Variable 'observed' used at line 427 is defined at line 425 and has a Short-Range dependency.
Variable 'goal' used at line 427 is defined at line 425 and has a Short-Range dependency.
Library 'Math' used at line 427 is defined at line 3 and has a Long-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 2, 'Library Long-Range': 1} |
infilling_java | DoubleVectorTester | 426 | 432 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {'] | [' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }'] | [' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 426}, {'reason_category': 'If Body', 'usage_line': 427}, {'reason_category': 'If Body', 'usage_line': 428}, {'reason_category': 'If Condition', 'usage_line': 428}, {'reason_category': 'If Body', 'usage_line': 429}, {'reason_category': 'Else Reasoning', 'usage_line': 430}, {'reason_category': 'If Body', 'usage_line': 430}, {'reason_category': 'Else Reasoning', 'usage_line': 431}, {'reason_category': 'If Body', 'usage_line': 431}] | Variable 'observed' used at line 426 is defined at line 425 and has a Short-Range dependency.
Variable 'goal' used at line 426 is defined at line 425 and has a Short-Range dependency.
Library 'Math' used at line 426 is defined at line 3 and has a Long-Range dependency.
Variable 'observed' used at line 427 is defined at line 425 and has a Short-Range dependency.
Variable 'goal' used at line 427 is defined at line 425 and has a Short-Range dependency.
Library 'Math' used at line 427 is defined at line 3 and has a Long-Range dependency.
Variable 'pos' used at line 428 is defined at line 425 and has a Short-Range dependency.
Variable 'observed' used at line 429 is defined at line 425 and has a Short-Range dependency.
Variable 'pos' used at line 429 is defined at line 425 and has a Short-Range dependency.
Variable 'goal' used at line 429 is defined at line 425 and has a Short-Range dependency.
Variable 'observed' used at line 431 is defined at line 425 and has a Short-Range dependency.
Variable 'goal' used at line 431 is defined at line 425 and has a Short-Range dependency. | {'If Condition': 2, 'If Body': 5, 'Else Reasoning': 2} | {'Variable Short-Range': 10, 'Library Long-Range': 2} |
infilling_java | DoubleVectorTester | 453 | 455 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {'] | [' pos++;', ' continue;', ' }'] | [' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 453}, {'reason_category': 'If Body', 'usage_line': 453}, {'reason_category': 'Loop Body', 'usage_line': 454}, {'reason_category': 'If Body', 'usage_line': 454}, {'reason_category': 'Loop Body', 'usage_line': 455}, {'reason_category': 'If Body', 'usage_line': 455}] | Variable 'pos' used at line 453 is defined at line 448 and has a Short-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Variable Short-Range': 1} |
infilling_java | DoubleVectorTester | 468 | 471 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm'] | [' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }'] | [' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'testMe' used at line 468 is defined at line 438 and has a Medium-Range dependency.
Variable 'init' used at line 468 is defined at line 438 and has a Medium-Range dependency.
Variable 'total' used at line 468 is defined at line 461 and has a Short-Range dependency.
Function 'checkCloseEnough' used at line 469 is defined at line 425 and has a Long-Range dependency.
Variable 'testMe' used at line 469 is defined at line 438 and has a Long-Range dependency.
Variable 'expected' used at line 469 is defined at line 468 and has a Short-Range dependency.
Variable 'expected' used at line 470 is defined at line 468 and has a Short-Range dependency. | {} | {'Variable Medium-Range': 2, 'Variable Short-Range': 3, 'Function Long-Range': 1, 'Variable Long-Range': 1} |
infilling_java | DoubleVectorTester | 523 | 524 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {'] | [' checkCloseEnough (testMe.getItem (i), init, i);', ' }'] | [' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 523}, {'reason_category': 'Loop Body', 'usage_line': 524}] | Function 'checkCloseEnough' used at line 523 is defined at line 425 and has a Long-Range dependency.
Variable 'testMe' used at line 523 is defined at line 515 and has a Short-Range dependency.
Variable 'i' used at line 523 is defined at line 522 and has a Short-Range dependency.
Variable 'init' used at line 523 is defined at line 515 and has a Short-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 3} |
infilling_java | DoubleVectorTester | 548 | 549 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {'] | [' ratios[i] = myVec.getItem (i) / result;', ' }'] | [' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 548}, {'reason_category': 'Loop Body', 'usage_line': 549}] | Variable 'myVec' used at line 548 is defined at line 539 and has a Short-Range dependency.
Variable 'i' used at line 548 is defined at line 547 and has a Short-Range dependency.
Variable 'result' used at line 548 is defined at line 542 and has a Short-Range dependency.
Variable 'ratios' used at line 548 is defined at line 546 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 4} |
infilling_java | DoubleVectorTester | 556 | 557 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' 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 absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of 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 ();', '}', '', '', '/**', ' * 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();', '}', '', '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 ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * 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, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {'] | [' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } '] | [' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 556}, {'reason_category': 'Loop Body', 'usage_line': 557}] | Function 'checkCloseEnough' used at line 556 is defined at line 425 and has a Long-Range dependency.
Variable 'ratios' used at line 556 is defined at line 546 and has a Short-Range dependency.
Variable 'i' used at line 556 is defined at line 555 and has a Short-Range dependency.
Variable 'myVec' used at line 556 is defined at line 539 and has a Medium-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 2, 'Variable Medium-Range': 1} |
completion_java | RNGTester | 145 | 148 | ['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 146 is defined at line 145 and has a Short-Range dependency.
Global_Variable 'seedValue' used at line 146 is defined at line 139 and has a Short-Range dependency.
Library 'Random' used at line 147 is defined at line 5 and has a Long-Range dependency.
Global_Variable 'seedValue' used at line 147 is defined at line 146 and has a Short-Range dependency.
Global_Variable 'rng' used at line 147 is defined at line 140 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 3, 'Library Long-Range': 1} |
completion_java | RNGTester | 153 | 155 | ['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 'next' used at line 153 is defined at line 18 and has a Long-Range dependency.
Global_Variable 'rng' used at line 154 is defined at line 140 and has a Medium-Range dependency. | {} | {'Function Long-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | RNGTester | 160 | 162 | ['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 'startOver' used at line 160 is defined at line 23 and has a Long-Range dependency.
Global_Variable 'rng' used at line 161 is defined at line 140 and has a Medium-Range dependency.
Global_Variable 'seedValue' used at line 161 is defined at line 139 and has a Medium-Range dependency. | {} | {'Function Long-Range': 1, 'Global_Variable Medium-Range': 2} |
completion_java | RNGTester | 190 | 192 | ['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': 190}, {'reason_category': 'Loop Body', 'usage_line': 191}, {'reason_category': 'Loop Body', 'usage_line': 192}] | Variable 'i' used at line 190 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'params' used at line 190 is defined at line 171 and has a Medium-Range dependency.
Function 'genUniform' used at line 191 is defined at line 531 and has a Long-Range dependency.
Variable 'myArray' used at line 191 is defined at line 189 and has a Short-Range dependency.
Variable 'i' used at line 191 is defined at line 190 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 3, 'Global_Variable Medium-Range': 1, 'Function Long-Range': 1} |
completion_java | RNGTester | 195 | 195 | ['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 'myArray' used at line 195 is defined at line 189 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1} |
completion_java | RNGTester | 289 | 290 | ['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 'myParams' used at line 289 is defined at line 287 and has a Short-Range dependency.
Global_Variable 'params' used at line 289 is defined at line 281 and has a Short-Range dependency.
Function 'setup' used at line 290 is defined at line 299 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1, 'Function Short-Range': 1} |
completion_java | RNGTester | 294 | 296 | ['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 294 is defined at line 293 and has a Short-Range dependency.
Variable 'myParams' used at line 295 is defined at line 293 and has a Short-Range dependency.
Global_Variable 'params' used at line 295 is defined at line 281 and has a Medium-Range dependency.
Function 'setup' used at line 296 is defined at line 299 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Medium-Range': 1, 'Function Short-Range': 1} |
completion_java | RNGTester | 309 | 311 | ['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': 'If Body', 'usage_line': 309}, {'reason_category': 'If Body', 'usage_line': 310}, {'reason_category': 'If Body', 'usage_line': 311}] | Class 'UnitGamma' used at line 309 is defined at line 588 and has a Long-Range dependency.
Function 'getPRNG' used at line 309 is defined at line 508 and has a Long-Range dependency.
Class 'GammaParam' used at line 309 is defined at line 246 and has a Long-Range dependency.
Variable 'leftover' used at line 309 is defined at line 307 and has a Short-Range dependency.
Global_Variable 'gammaShapeLessThanOne' used at line 309 is defined at line 285 and has a Medium-Range dependency.
Global_Variable 'params' used at line 310 is defined at line 281 and has a Medium-Range dependency.
Global_Variable 'params' used at line 311 is defined at line 281 and has a Medium-Range dependency. | {'If Body': 3} | {'Class Long-Range': 2, 'Function Long-Range': 1, 'Variable Short-Range': 1, 'Global_Variable Medium-Range': 3} |
completion_java | RNGTester | 320 | 322 | ['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': 320}, {'reason_category': 'Loop Body', 'usage_line': 321}, {'reason_category': 'Loop Body', 'usage_line': 322}] | Variable 'i' used at line 320 is defined at line 320 and has a Short-Range dependency.
Global_Variable 'numShapeOnesToUse' used at line 320 is defined at line 283 and has a Long-Range dependency.
Global_Variable 'gammaShapeOne' used at line 321 is defined at line 284 and has a Long-Range dependency.
Variable 'value' used at line 321 is defined at line 319 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 2} |
completion_java | RNGTester | 324 | 324 | ['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': 'If Body', 'usage_line': 324}] | Global_Variable 'gammaShapeLessThanOne' used at line 324 is defined at line 285 and has a Long-Range dependency.
Variable 'value' used at line 324 is defined at line 319 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | RNGTester | 347 | 347 | ['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 'shapes' used at line 347 is defined at line 336 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
completion_java | RNGTester | 351 | 351 | ['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 'leftmostStep' used at line 351 is defined at line 337 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
completion_java | RNGTester | 355 | 355 | ['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 'numSteps' used at line 355 is defined at line 338 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
completion_java | RNGTester | 374 | 376 | ['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 'prng' used at line 374 is defined at line 373 and has a Short-Range dependency.
Variable 'myParams' used at line 375 is defined at line 373 and has a Short-Range dependency.
Global_Variable 'params' used at line 375 is defined at line 365 and has a Short-Range dependency.
Function 'setup' used at line 376 is defined at line 299 and has a Long-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1, 'Function Long-Range': 1} |